text:
Q: Yocto - create mImage kernel format Hardware platform: RaspberryPi 4B. I want to create mImage kernel format using Yocto. I see that only allowed values for variable KERNEL_IMAGETYPE are zImage and Image. So I tried to write custom function that will create mImage format. But I struggling with dependency erros.
This is recipe of my image:
require recipes-core/images/core-image-minimal.bb
IMAGE_NAME = "super-pi"
IMAGE_INSTALL:append = " kernel-modules"

IMAGE_FSTYPES:append = " wic.gz"
IMAGE_FSTYPES:append = " ${INITRAMFS_FSTYPES}"
IMAGE_INSTALL += "testm"

do_create_mimage[nostamp] = "1"
do_create_mimage[depends] += "virtual/kernel:do_deploy"

addtask do_create_mimage after do_deploy before do_build

do_create_mimage() {
    bbnote "<super-pi> Building mImage"
    bbnote "deploy dir: ${DEPLOY_DIR_IMAGE}"
    bbnote "uboot build dir: ${UBOOT_BUILD_DIR}"
    ${UBOOT_BUILD_DIR}/tools/mkimage -C none -A ${ARCH} -O linux -T multi -a 0x88000000 -e 0x88000000 \
    -d ${DEPLOY_DIR_IMAGE}/Image:${DEPLOY_DIR_IMAGE}/super-pi-
    initramfs.cpio:${DEPLOY_DIR_IMAGE}/bcm2711-rpi-4-b.dtb ${DEPLOY_DIR_IMAGE}/mImage
}

I defined UBOOT_BUILD_DIR in local.conf and it points to U-Boot B directory.
The problem is when function do_create_mimage is executed there is mkimage can't find super-pi-initramfs.cpio image (I wrote recipe for this image). Error message:
ERROR: super-pi-1.0-r0 do_create_mimage:
ExecutionError('/home/kuba/Desktop/YOCTO/build/tmp/work/raspberrypi4-poky-linux-gnueabi/super-
pi/1.0-r0/temp/run.do_create_mimage.39881', 1, None, None)
ERROR: Logfile of failure stored in: /home/kuba/Desktop/YOCTO/build/tmp/work/raspberrypi4-
poky-linux-gnueabi/super-pi/1.0-r0/temp/log.do_create_mimage.39881
Log data follows:
| DEBUG: Executing shell function do_create_mimage
| NOTE: <super-pi> Building mImage
| NOTE: deploy dir: /home/kuba/Desktop/YOCTO/build/tmp/deploy/images/raspberrypi4
| NOTE: uboot build dir: /home/kuba/Desktop/YOCTO/build/tmp/work/raspberrypi4-poky-linux-
gnueabi/u-boot/1_2022.01-r0/build
| /home/kuba/Desktop/YOCTO/build/tmp/work/raspberrypi4-poky-linux-gnueabi/u-boot/1_2022.01-
r0/build/tools/mkimage: Can't stat
/home/kuba/Desktop/YOCTO/build/tmp/deploy/images/raspberrypi4/super-pi-initramfs.cpio: No such
file or directory
| WARNING: exit code 1 from a shell command

Where should I place function do_create_mimage() so that all dependencies are met before this function call?
I checked log.task_order for super-pi image:
. . .
do_image_tar (39740): log.do_image_tar.39740
do_image_ext3 (39741): log.do_image_ext3.39741
do_rootfs_wicenv (39747): log.do_rootfs_wicenv.39747
do_image_cpio (39742): log.do_image_cpio.39742
do_create_mimage (39881): log.do_create_mimage.39881
do_image_wic (39884): log.do_image_wic.39884

It looks like my task is executed after cpio image should be ready, but it sill can't find it.


text:
Q: Adding my type declaration throws an error "Typescript emitted no output for my.d.ts" Compiling TypeScript with my own type declaration file (let's say my.d.ts) gives me an error saying "Typescript emitted no output for my.d.ts".
Of course, I don't expect any code generated from this type declaration file.
my.d.ts has only interface definition like this.
interface JQueryStatic {
    request(handler: string, options: any): any;
}

A: There might be many other cases, but the problem in my case was that the location of my .d.ts file.
I put my .d.ts file in the same directory as other .ts files, and my configuration included the .d.ts file as compile target.
Moving .d.ts file to outside of the directory of compile target fixed this problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Invisible runtime errors in threads I am writing a C++ application for an embedded Linux. I have a problem where runtime errors, like unhandled exceptions and segmentation faults, that occur in threads other than the main thread are not displayed in the console. In such cases my application will be terminated abruptly without any error message. Is there any way to get the error messages to the default console of the parent main thread? (gdb is not supported on my embedded linux)

A: You shouldn't let exceptions propagate out of your thread function.  Typically you would have a catch all exception handler around the body of your thread function.  How you handle these exceptions is then down to you.

A: I found out that these runtime-errors are displayed in the syslog files, that completely fulfills my requirements.


text:
Q: Taylor expansion of $\ln(1+\frac{x}{n})$ I want to use Taylor's Theorem to show that $\ln(1+\frac{x}{n}) = \frac{x}{n}+O\frac{x^2}{n^2}$ (I cannot use $\ln(1+x) = \sum_{n=1}^{\infty}(-1)^{n}\frac{x^n}{n}$ in this question).
My attempt:
Apply Taylor's Theorem, for each pair of points $x,x_0 \in (a,b)$, $\exists c \in (x,x_0)$ s.t.
$$
\ln(1+\frac{x}{n}) = f(x_0)+f'(x_0)(x-x_0)+\frac{f''(c)}{2!}(x-x_0)^2 \\
= \ln(1+\frac{x_0}{n})+\frac{x-x_0}{n+x_0}-\frac{(x-x_0)^2}{2!(n+c)^2}
$$
This does not seem to align with $ \frac{x}{n}+O\frac{x^2}{n^2}$, any idea on how to approach this?

A: You're very close. Put $x_0 = 0$ and $1/(n+c)^2 = O(1/n^2) $.


text:
Q: Jquery function is working just on first element, I want to work on all classes I've created a Jquery function that looks like this
jQuery(document).ready(function ($) {

var animations = document.querySelectorAll('.slide-up');
for (var i = 0; i < animations.length; i++) {
    var windowHeight = window.innerHeight;
    var elementTop = animations[i].getBoundingClientRect().top;
    var elementVisible = 140;

    if (elementTop < windowHeight - elementVisible) {
        animations[i].classList.add("active");
    }
    else {
        animations[i].classList.remove("active");
    }
}});

The problem is, it is working just on the first class when I'm scrolling down, I want to work on each class.I also try something like:
jQuery(document).ready( function($){
$('slide-up').each(function($) {
    var animations = document.querySelectorAll('.slide-up');
    for (var i = 0; i < animations.length; i++) {
        var windowHeight = window.innerHeight;
        var elementTop = animations[i].getBoundingClientRect().top;
        var elementVisible = 140;

        if (elementTop < windowHeight - elementVisible) {
            animations[i].classList.add("active");
        }
        else {
            animations[i].classList.remove("active");
        }
    }
});});

But with same results.Any ideas or suggestion about how to apply to all elements that have .slide-up class when I'm scrolling down ?
Thanks in advance !

A: Consider the following.
jQuery(function($) {
  var animations = $('.slide-up');
  var windowHeight = window.innerHeight;
  var elementVisible = 140;
  animations.each(function(i, el) {
    var elementTop = $(el).position().top;
    if (elementTop < windowHeight - elementVisible) {
      $(el).toggleClass("active");
    }
  });
});

This should perform an action on each element. All code has been switched to jQuery.


text:
Q: apache2: render web pages I am having following configuration in my apache2.conf:
ScriptAlias /cgi-bin/ "/var/www/temp/pages"

<Directory "/var/www/temp/pages/">
  AllowOverride None
  Order allow,deny
  Allow from all
</Directory>

<Directory "/var/www/temp/scripts/">
  AllowOverride None
  Options ExecCGI
  Order allow,deny
  Allow from all
</Directory>

The intention is that in one directory I store my web pages and in another - the scripts. I have a sample index.html file placed in /var/www/temp/pages/ dir but when I try to access from browser:
<ip>/cgi-bin/index.html

I get below error:
Exec format error ....
Prematrure end of script

How can I fix this issue?


text:
Q: How does iOS 7 implement the UI elements so that they look different depending on what SDK you compile with? There are elements like UITableViews, UINavigationBars that have a different style on iOS 7.
This style is determined at run time, since those classes are implemented on UIKit, and UIKit is linked with your application dynamically at runtime, not statically at compile time.
So one would think that any app run on iOS 7 would have those elements look the way they look on iOS 7. However, they keep the same style they used to have on iOS 6, until you compile with the iOS 7 SDK. Except for some of them (like UIAlertView or UIMenuController)
My only explanation for this is that they do something kind of like this:
#define SDKApplicationWasLinkedAgainst ...
if (SDKApplicationWasLinkedAgainst < 7.0)
    ...
else
    ...

This is obviously really cumbersome, cause they need to keep maintaining a lot of old code. So I'm curious, is this really what is going on under the hood? What am I missing?

A: Without going too much into NDA'd territory, I'd just like to state that yes, they are conditionalizing appearance and behavior based off of the result from the following call:
_UIApplicationUsesLegacyUI()

This function, in turn, makes a call to GSApplicationUsesLegacyUI(), which I presume returns a result based off of the version of the linked UIKit.
This means that yes, they are conditionalizing parts of UIKit for legacy. Not sure that's a good thing, but that's what they decided to do.

A: My bet is that they use framework compatibility versions.
Each time you compile your app, your app is linked against an specific framework, with compatibility version and current version. You can see those numbers if you run otool -L YourApp.app/YourApp. For example, for an application compiled some time ago I obtained this:
/System/Library/Frameworks/Foundation.framework/Foundation (compatibility version 300.0.0, current version 751.58.0)
/System/Library/Frameworks/UIKit.framework/UIKit (compatibility version 1.0.0, current version 1500.0.0)

As you can see the full path of the UIKit framework is stored in the Mach-O binary, along a couple of versions (and specially the version I compiled against at that moment).
I suppose that iOS 7 will have both UIKit version included: the one from iOS6 marked with the corresponding version and saying compatibility from 1.0.0, and the one from iOS7 marked as compatible with something higher than 1500.0.0 (I don't know if that's the number for iOS 6.1.3, but you get the idea).
When your iOS6 binary is loaded, its library dependencies are read by dyld and resolved, because you were compiled saying current version 1500.0.0, and the library for iOS 7 says compatibility version 1501.0.0, you will be linked against the library for iOS 6.
Since a framework is also a bundle, all the resources are perfectly contained, and will be used only by the right version, and that's how the different visual elements will look different if you compile against iOS 6 SDK or iOS 7 SDK.
I might be wrong, but I simply hope they are not using the code technique you propose, because that will be a crappy code base to maintain.

A: I can't be certain, but this is one guess about how it is done. Because they know what SDK version your app was linked against, they version out the framework on iOS 7 devices. So there is a hierarchy on the filesystem along the lines of /.../iPhoneOS6.1.sdk/.../Frameworks/UIKit. Then when it loads your app, they can just set the search path for libraries to point to whichever SDK your app was linked against.
This is how Xcode does it right now. Inside the Developer directory inside the Xcode package is an SDKs directory, which, in turn, contains all the different SDKs to link against.


text:
Q: Assembly x86 putting values into array with loop I wanted to put numbers in an array of length 10, but each number is 1 bigger than the last number.
It means: myArray = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
I have tried this:

IDEAL
  MODEL small
  STACK 100h
DATASEG
intArray db 10 dup (0)
  index db 1
CODESEG
start:
    mov ax, @DATA
    mov ds, ax
  loopArray:
    mov al, [index]
    add [intArray+index], al ; here is the problem
    inc [index]
    cmp [index], 11
    jb loopArray
  exit:
    mov ax, 4c00h
    int 21h
  END start

But I can't add the index to [intArray + index], so I tried to to add it to [intArray+al], and that doesn't work either.
How can I add the index to the next array's value each time?

A:
myArray = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.

These are the numbers that you want your array to contain. But since you initialized the index variable (that you will be using for both indexing and storing) as 1 (using index db 1) this will lead to another result.
Just setup the index with:
index db 0

There's another reason to set it up this way!
In the notation [intArray+index] the index part is meant to be an offset in the array. Offsets are always zero based quantities. The way you wrote your program, it will write the 10th value behind the array.

add [intArray+index], al ; here is the problem

You're right that this is the problem. Some assemblers won't compile this, and others will just add the addresses of both these variables. Neither suits your purpose. What you need is putting the content of the index variable in a register and use that combination of operands.
    intArray db 10 dup (0)
    index    db 0
    ...
loopArray:
    movzx    bx, [index]
    mov      [intArray+bx], bl ;Give the BX-th array element the value BL
    inc      [index]
    cmp      [index], 10
    jb       loopArray

With this code the index will start at 0 and then the loop will continu for as long as the index is smaller than 10.

Of course you could write this program without using an index variable at all.
    intArray db 10 dup (0)
    ...
    xor      bx, bx            ;This make the 'index' = 0
loopArray:
    mov      [intArray+bx], bl ;Give the BX-th array element the value BL
    inc      bx
    cmp      bx, 10
    jb       loopArray

Given that the array was initially filled with zeroes, you can replace the:
    mov      [intArray+bx], bl ;Give the BX-th array element the value BL

with:
    add      [intArray+bx], bl ;Give the BX-th array element the value BL

Do remember this can only work if the array was filled with zeroes beforehand!


text:
Q: Is Stored javascript in mongodb, atomic? If I call the following stored-function from server:
Assume that, insertation of bEntity failed. In this situtation, does added aEntity roll back to the its old state?
function areYouAnAtomicOperation(x)
{
db.aEntity.insert ({a:x});
db.bEntity.insert ({b:x});
db.cEntity.insert ({c:x});
}

Any method, for making this function atomic in mongodb?

A: No, it's not atomic. Here is a list of atomic operations.
If it's really really really important you can manually emulate two-phase commit semantics but be warned that it's really complicated.
If transactions are important, you better use some other database (an RDBMS?) which provides it.


text:
Q: multiple viewclass (Kivy - Recycleview) I'm implementing a recycleview in kivy. It is possible have multiple (one or more) viewclass depending the dataset data? i would like to have in the same list multiple layouts (eg. one line viewclass1 (one label and two buttons) and another line viewclass2 (one label and two TextInput). Thank you.

A: You can create a widget that extends a layout and then you could add the widgets you need programmatically.

A: I don't think you can have lines with different viewclasses in a single RecycleView. RecycleView ,by design, has only one viewclass because it is meant for a large collection of homogeneous items.
For what you are looking for the most straightforward way is probably to use ScrollView and to define a custom add_line(self, type): function to dynamically add each line specifying the type.


text:
Q: Avoiding Mocha timeout on assertion error with SuperTest? I have some Sails.js API tests (using Mocha) that make use of SuperTest's .end() method to run some Chai assertions on the response.
I call the test's done() callback after the assertions, but if an assertion error is thrown, the test times out.
I can wrap the assertions in a try/finally, but this seems a bit icky:
var expect = require('chai').expect;
var request = require('supertest');

// ...

describe('should list all tasks that the user is authorized to view', function () {

  it('the admin user should be able to see all tasks', function (done) {
    var agent = request.agent(sails.hooks.http.app);
    agent
      .post('/login')
      .send(userFixtures.admin())
      .end(function (err, res) {
        agent
          .get('/api/tasks')
          .expect(200)
          .end(function (err, res) {
            try {
              var tasks = res.body;
              expect(err).to.not.exist;
              expect(tasks).to.be.an('array');
              expect(tasks).to.have.length.of(2);
            } finally {
              done(err);
            }
          });
      });
  });
});

Any suggestions on how to better deal with this? Perhaps Chai HTTP might be better?

A: According to Supertest's documentation, you need to check for the presence of err and, if it exists, pass it to the done function. Like so
.end(function (err, res) {
    if (err) return done(err);

    // Any other response-related assertions here
    ...

    // Finish the test
    done();
});

A: You can pass out login logic from test.
// auth.js
var request = require('supertest'),
    agent = request.agent;

exports.login = function(done) {
    var loggedInAgent = agent(sails.hooks.http.app);
    loggedInAgent
        .post('/login')
        .send(userFixtures.admin())
        .end(function (err, res) {
            loggedInAgent.saveCookies(res);
            done(loggedInAgent);
        });
};

And then just use it in your test:
describe('should list all tasks that the user is authorized to view', function () {

    var admin;

    before(function(done) {
        // do not forget to require this auth module
        auth.login(function(loggedInAgent) {
            admin = loggedInAgent;
            done();
        });
    });

    it('the admin user should be able to see all tasks', function (done) {

        admin
            .get('/api/tasks')
            .expect(function(res)
                var tasks = res.body;
                expect(tasks).to.be.an('array');
                expect(tasks).to.have.length.of(2);
            })
            .end(done);

    });

    it('should have HTTP status 200', function() {

        admin
            .get('/api/tasks')
            .expect(200, done);

    });

});

With such approach you should not login your admin for each test (you can reuse your admin again and again in your describe block), and your test cases become more readable.
You should not get timeouts with this approach because .end(done) guaranties that your test will finish without errors as well with them.


text:
Q: Django Rest Framework: issue with request.data I am attempting to use Django rest framework for my server implementation.  I get the following error when I attempt to POST.
'WSGIRequest' object has no attribute 'data'

Here is the code for the view.py
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from whiteboards.models import Whiteboard, Path, Point
from whiteboards.serializers import WhiteboardSerializer

@api_view(['GET', 'POST'])
def whiteboard_list(request):
   """
   List all whiteboards, or create a new whiteboard.
   """

   if request.method == 'GET':
       print('GET')
       whiteboards = Whiteboard.objects.all()
       serializer = WhiteboardSerializer(whiteboards, many=True)
       return Response(serializer.data)

   elif request.method == 'POST':
       print('POST')
       d = request.data
       print('data broke')
       serializer = WhiteboardSerializer(data=d)
       print("created serializer")
       if serializer.is_valid():
           serializer.save()
           print("It's valid")
           return Response(serializer.data, status=status.HTTP_201_CREATED)
       return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

A: try request.DATA instead of request.data

A: In version 3 (latest) - request.DATA has been replaced with request.data:
user = dict(
                    full_name=request.data['full_name'],
                    password=request.data['password'],
                    email=request.data['email']
                )

In version 2 - it was request.DATA:
user = dict(
                full_name=request.DATA['full_name'],
                password=request.DATA['password'],
                email=request.DATA['email']
            )


text:
Q: Drupal content type add class to image field (on link, not on image) I have a content type (i.e.: Toys)
Some fields are added including an 'images'-field.
In the display settings:
1/ link image to file
"Field formatter class" will add a class to the img-tag but I want the class on the a-tag.
How?
in template.php?? preprocess_node? preprocess_image?
Please help.
Thx.

A: You may want to check out the theme_field API at https://api.drupal.org/api/drupal/modules!field!field.module/function/theme_field/7 and look at the examples.
Drupal core's field.module is what adds classes to fields.  You can either use a function in template.php or a tpl.php file to override it.


text:
Q: Why is there infinite recursion when I apply a function with the argument n-1 (no parentheses), inside the application of another function? Here I can pass to function f the argument 7-1, without parentheses.
Prelude> f = (+1)
Prelude> f 7-1
7

1.
Why is the following an infinite recursion?
Prelude> addRec :: (Eq a, Num a) => a -> a; addRec 0 = 0; addRec n = n + addRec n-1;
Prelude> addRec 5

2.
I can fix it by either adding parentheses to n-1
Prelude> addRec :: (Eq a, Num a) => a -> a; addRec 0 = 0; addRec n = n + addRec (n-1);

3.
Or by using the $ operator with parentheses on the whole addRec recursion term:
Prelude> addRec :: (Eq a, Num a) => a -> a; addRec 0 = 0; addRec n = n + (addRec $ n-1)

I'd like to understand exactly how each expression works or doesn't work.
Here is my line of reasoning:
In addRec n = n (...) we are effectively composing two function (without using the . composition operator). We are composing (+) and addRec. Is Haskell in this example understanding we have a third function (-)?
We are using function application (which as far as I understand is the operator represented by a whitespace after a function) to achieve this composition.
Function application is left associative, so my first question is: what does addRec n = n + addRec n-1 look like when we add the parentheses corresponding to the default left associativity?

A: f 7-1 doesn't mean what you think it means.
In Haskell, function application has the highest priority. This means that f 7-1 is always interpreted as (f 7) - 1. The absence of a space around the minus sign is irrelevant, and it is only by coincidence that you get the correct answer: f 7 = (+ 1) 7 = 8, and then 8 - 1 = 7. This would not happen if your function was defined as f = (* 2).
Similarly, addRec n-1 is interpreted as (addRec n) - 1, thus calling addRec with the same argument n every time, producing infinite recursion.
The two ways to fix it, you already know: parens or operator $.


text:
Q: Problema en actualizar Array en React Native tengo este problema al querer recargar el arreglo desde otra pantalla,
Pantalla del detalle donde al agregar un comentario se actualiza esta pantalla, pero solamente se actualiza ésta. En cambio a la pantalla de Home no se actualiza.
HomeDetalle:
state = {
  Post: {
    PostId: 0,
    PostComment: '',
    PostedBy: '',
    ImageId: 0,
    PostedOn: new Date(),
    UserId: 0,
    Comments: [] as PostComment[],
    LikesCount: 0,
  },
  textoComentario: '',
  onPostRefresh: (post: Post) => {},
};

constructor(props: Props) {
  super(props);
  this.state = {
    Post: props.route.params.Post,
    textoComentario: '',
    onPostRefresh: props.route.params.onPostRefresh,
  };
}

formatDate(input: Date): string {
  return moment(input).locale('es').startOf('hour').fromNow()
}

async PublicarComentario() {
  const muroService = new MuroService();
  const postId = this.state.Post.PostId;
  const model: PublicarComentario = {
    PostId: postId,
    Comment: this.state.textoComentario
  }
  const response = await muroService.PublicarComentario(model);

  if(!response.OperationSuccesful) {
    Alert.alert(response.ErrorMessage);
  } else {
    Alert.alert("Haz publicado un comentario");
  }
  this.setState({
    Post: response.Post,
    textoComentario: '',
  });

}

goBack() {
  this.props.navigation.goBack();
  this.state.onPostRefresh(this.state.Post);
}

Aquí tengo mi funcion para actualizar mi componente llamado Posts en la pantalla
Home:
actualizarPost(post: Post) {
  const Post = this.state.Posts.findIndex(e => e.PostId === post.PostId);
  let postCopy = [...this.state.Posts];
  postCopy[Post] = {...this.state.Posts[Post]}
  this.setState({
    Posts: postCopy.concat(post)
  })
}

Ya revisé debuggeando que funciona todo bien, el post en el actualizarPost() funciona de manera correcta, se trae el post actualizado pero al momento de querer hacer un setState no me funciona, alguien tiene alguna idea de que puedo hacer?
Comparto el .map en pantalla Home:
     {
        this.state.Posts.map((post: Post, index:number) => (
          <PostComponent navigation={this.props.navigation} Post={ post } onPostSelected={ this.onPostSelected } key={ post.PostId + '' } ></PostComponent>
        ))
      }

En mi componente PostComponent tengo esto funcionando de manera correcta:
<TouchableOpacity onPress={() => { this.props.onPostSelected(this.props.Post); }

Tambien tengo esto en mi pantalla Home para mandar en la navegacion un onPostRefresh con la funcion this.actualizarPost para que regrese con el Post actualizado:
onPostSelected(post: Post) {
  this.props.navigation.navigate("HomeDetalle", { Post: post, onPostRefresh: this.actualizarPost  } );
}

A: Cuando usas una función dentro de this.setState(...) este debe retornar el nuevo valor que quieres se setee en tu state, pero en tu ejemplo no retorna nada.
Esto debería funcionar
actualizarPost(post: Post) {
  this.setState(prevState => {
    return {
      ...prevState, // se mantienen las otras llaves
      Posts: prevState.Posts.concat(post) // se sobreescribe el campo Posts
    }
  })
}

Espero te sirva!

A: Resolví el problema haciendo esto:
actualizarPost(post: Post) {
  this.actualizarListado();
}

Y poniendo esto en componentDidMount()
async componentDidMount() {
  this.actualizarListado();
}

async actualizarListado() {
  // code
}


text:
Q: Paypal Sandbox payment problem I have the following post button that i use for paypal transactions:
    <form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
        <input type="hidden" name="cmd" value="_xclick">
        <input type="hidden" name="business" value="my@email.com">
        <input type="hidden" name="item_name" value="Item description">
        <input type="hidden" name="item_number" value="1">
        <input type="hidden" name="amount" value="00.30">
        <input type="hidden" name="no_shipping" value="1">
        <input type="hidden" name="no_note" value="1">
        <input type="hidden" name="currency_code" value="USD">
        <input type="hidden" name="lc" value="US">
        <input type="hidden" name="bn" value="PP-BuyNowBF">
        <input type="hidden" name="return" value="website.com/index.php" />
        <input type="hidden" name="cancel_return" value="website.com/index.php" />
        <input type="hidden" name="rm" value="2">
        <input type="hidden" name="notify_url" value="website.com/ipn/ipn.php">
        <input type="hidden" name="custom" value="user_id">
        <input type="submit" value="upgrade" />
    </form>

and the following code in ipn.php
<?php
include_once 'config.php';
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';

foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}

// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
    //$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];

if (!$fp) {
// HTTP ERROR
} else {
    fputs ($fp, $header . $req);
    while (!feof($fp)) {
        $res = fgets ($fp, 1024);
        if (strcmp ($res, "VERIFIED") == 0) {
            // check the payment_status is Completed
            // check that txn_id has not been previously processed
            // check that receiver_email is your Primary PayPal email
            // check that payment_amount/payment_currency are correct
            // process payment
            mysql_query("UPDATE table SET column='1' WHERE column2='13'");
        }
        else if (strcmp ($res, "INVALID") == 0) {
            // log for manual investigation
        }
    }
fclose ($fp);
}
?>

when i click the upgrade button and pay, it doesnt show me a go back to the website button... but there is a go back to my@email.com button, which has a 10 sec delay and takes me back to my website... although it popups a warning about encrypted data, which i dont know what it is.
Also the query i use in ipn.php does not execute.I dont even know if it goes to ipn.php.

A: Regarding go back to "my@email.com", this could happen if the email you specified doesn't map to an account in the PayPal sandbox. Perhaps you're using your real email in the button instead of a sandbox account email?
Another possibility is that your test account at "my@email.com" is not a business account. If you have a business account it should reflect your business name instead.
As for not receiving the IPNs, the sandbox doesn't always do a great job at delivering IPNs on time, if at all. I'd actually suggest that you try integrating using Express Checkout instead of Website Payments Standard. Express Checkout is a little bit of a confusing dance initially but it is easy to implement after you try to understand it. Here's what I think is the best doc explaining how Express Checkout works:
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_ECSimpleIntegration
And when you're ready to dive into the implementation you should look here:
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/howto_api_reference
The nice thing about using Express Checkout instead of relying on IPN is that you get to figure out the payment status the moment your user returns to your site, and you don't have to sit around waiting for the IPN to show up.
With Express Checkout you also get to override your business name with a custom "brand name" so you can use the same receiving PayPal account on different sites with different "brands".
Good luck!


text:
Q: How to change color when hover over div id? I have made a div id in my html and draw the bars in my css.
Now i want to change the colors when hover over the bars.
here is a example of my html
<div id="balklongwaarde">
</div>

And here is my css where I draw the divs
#balklongwaarde{
height: 150px;
width: 40px;
border: 1px solid #2e9afe;
background: #2e9afe;
position: absolute;
margin-top: 200px;
margin-left: 200px;
}

How to change the background color when hover over the bars?

A: in css
 #balklongwaarde:hover{background-color:red;}


text:
Q: How to get all images(overlapping allowed) in one line using css? I have a few images(3) which should be displayed in one line and whose combined width is MORE than the page width. But i anyway want them be overlapping, hence the page width doesn't matter. But for some reason only 2 images are coming in one line and third in the next. How do i sort this out.
They work perfectly if i make .imageContainer as position:abolute and give left:--px values to each of the id. But that would be difficult to maintain and align. Also they align up properly if i reduce the width of each image, but i don't want to do that :( . Please Help.

UPDATE
white-space:nowrap; placed in allImagesContainer has solved this problem, but only in chrome. The problem persists in FF and IE.
Here's the code:

And here's the styling:
.allImagesContainer {
position: relative;
top: 50px;
width: 80%;
height: 500px;
margin-left: auto;
margin-right: auto;
display: table ;
}

.imageContainer{
position: relative;
display: inline-block;
}

#firstImage{
z-index: 1;
}

#biggerImage{
position: relative;
left: -50px;
z-index: 2;
}

#lastImage{
position: relative;
left: -40px;
z-index: 1;
}

A: white-space:nowrap; is what you're looking for, placed in allImagesContainer
See a DEMO

A: If you don't want line breaks, you can use this css on allImagesContainer
.allImagesContainer
{
  white-space:nowrap;
}

Your can remove the position: absolute and relative on all the elements but keep the display:inline-block


text:
Q: php printing and updation in to db I have few values existing in data base,i need to update them but,i am unable to do it.

UPDATE Phone SET dcno='1' WHERE number='1' AND date='12/03/2009' AND dcnodate='11/05/2009' AND yourorderno='1' AND orderdate='23/06/2010' AND vendorcode='2222

Couldn't execute query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''2222' at line 3
I also need to print 3db value in to one form,i m unable to do it.
Any help ii be appreciated.
http://dpaste.com/hold/185341/

A: looks to me like you're missing the ' from the 2222.
try running that query in your database see what happens

A: There is a missing quote at the end:
vendorcode='2222

In the code the quote is missing at two places where UPDATE is being used:
....vendorcode='{$good_data['vendorcode']}'";

A: You are missing ending quote for last parameter:
"... AND vendorcode='{$good_data['vendorcode']}'";

To prevent such errors in future you should use mysqli_prepare with mysqli_stmt_bind_param. You'll find example on manual page.

A: Here would be two solutions.
1) add vendorcode='2222';
2) remove vendorcode=2222;


text:
Q: What is the underlying connection mode when using live connection? (import or direct query mode)
Live connections
When connecting to SQL Server Analysis Services,
there's an option to either import data from or connect live to, the
selected data model. If you use import, you define a query against
that external SQL Server Analysis Services source, and the data is
imported as normal. If you use connect live, there's no query defined,
and the entire external model is shown in the field list.

My understanding was that import/direct query can be used to query a data source like SQL server. Where as live mode is used to connect to an existing power bi dataset, or SSAS, or azure analysis service.
The above quote says When connecting to SQL Server Analysis Services, there's an option to either import data from or connect live to, the selected data model. - So does this mean that the live mode allows us to choose between import/direct query to the live model?

A:
When connecting to SQL Server Analysis Services, there's an option to
either import data from or connect live to, the selected data model.

This quote means that you do not have to use a live connection with SSAS models.  Instead you can construct a query and import the data.  The dataset would be limited to whatever was in the query.  If you use a live connection, you have access to the entire model.


text:
Q: Taking the limit of the bounds of an integral I need to prove that
$$\lim_{{\Delta \omega}\rightarrow 0^+} \int_{-\pi/\Delta \omega}^{\pi/\Delta \omega} f(\Delta \omega, t) dt = \lim_{{\Delta \omega}\rightarrow 0^+} \int_{-\infty}^{\infty} f(\Delta \omega, t) dt\label{eq:1}$$
Now, I know the composite limit theorem, which states that:
$$\lim_{u\rightarrow M} f(u) = \lim_{x\rightarrow a} f(g(x)) $$ Given that the following holds:
$$\lim_{x\rightarrow a} g(x) = M , \hspace{5mm} \lim_{u\rightarrow M} f(u) = f(M).$$
One can also derive the following property:
$$ \lim_{x\rightarrow a} \left[ f(x) g(x) \right] = \lim_{x\rightarrow a} \left[ K g(x) \right]  $$
Given that $$\lim_{x\rightarrow a}f(x) = K, \hspace{5mm} \lim_{x\rightarrow a}f(x) = L.$$
Is it possible to prove the first equality using these two limit theorems? I'm having doubts about applying the composite limit theorem, as $\int_{-\pi/\Delta \omega}^{\pi/\Delta \omega} f(\Delta \omega, t) dt$ is a functional and not a function. Does there exist an equivalent composite limit theorem for functionals?

A: I think you should impose some conditions on $f$.
For example, define $f : \mathbb R^2 \to \mathbb R$ by $f(\Delta w, t)= \Delta w\exp\left(-(\Delta w)^2 t^2 \right)   $.
Then for $\Delta w >0 $\begin{align} \int_{-\pi/\Delta w}^{\pi/\Delta w}f(\Delta w, t) dt &= \Delta w\int_{-\pi/\Delta w}^{\pi/\Delta w}\exp \left( -(\Delta w)^2 t^2 \right)dt \\ &= \Delta w\int_{-\pi}^{\pi}\exp\left(-s^2\right)\frac{1}{\Delta w}ds \\&=\int_{-\pi}^{\pi}\exp\left(-s^2\right)ds\end{align}
Here change of variables $s=(\Delta w)t$ is used.
On the other hand, \begin{align} \int_{-\infty}^{\infty}f(\Delta w, t) dt &= \Delta w\int_{-\infty}^{\infty}\exp \left( -(\Delta w)^2 t^2 \right)dt \\ &= \Delta w\int_{-\infty}^{\infty}\exp\left(-s^2\right)\frac{1}{\Delta w}ds \\&=\int_{-\infty}^{\infty}\exp\left(-s^2\right)ds\end{align}
Both integration are independent of $\Delta w$. Therefore $$\lim_{\Delta w \to 0+}\int_{-\pi/\Delta w}^{\pi/\Delta w}f(\Delta w, t) dt = \int_{-\pi}^{\pi}\exp\left(-s^2\right)ds \neq \int_{-\infty}^{\infty}\exp\left(-s^2\right)ds = \lim_{\Delta w \to 0+} \int_{-\infty}^{\infty}f(\Delta w, t) dt $$


text:
Q: Github not loading all resources I'm trying to pull this webpage to recreate my own startpage from 4chan's /wg/. The issue I'm having is that it isn't loading all the resources from the directory. Instead, this is what it looks like. Any idea how to fix this issue?
Due to my low reputation, I can't add more links, but the direct repository is available from the links already provided. It seems as the the *.js files are not being uploaded. Any idea why github isn't allowing me to upload those files?


text:
Q: Combine(Concatenate) two columns to third(PK) on insert query, sql server 2014 I am using sql server 2014 for windows form application,I have columns like this
id | AccountNo | Location
COLUMN DETAILS:
id ---> int, not null, auto increment
AccountNo ---> varchar(50), not null, Primary Key
Location --->  varchar(50), not null
I am want to run sql INSERT query to enter user input so that it would be like this
| id     | AccountNo | Location|
| 10000  | PK10000   | PK      |
I am thinking the QUERY LIKE THIS
string strCommand ="INSERT INTO Customer(ID, AccountNo, Location) values (@ID, CONCAT(@Location, @ID [, @AccountNo]), @Location)";
Or is it possible to create an trigger which would combine two columns at insert if it is not possible this way as the AccountNo is PK
Suggestions please..

A: You really shouldn't concatenate like this for primary key values. For example, you could get duplicate values. It's better to create an IDENTITY column to be the primary key. If you really need the extra column for display purposes, then add a computed column. For example:
CREATE TABLE MyTable
(
    ID INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
    Location VARCHAR(20) NOT NULL,
    AccountNo AS CAST(ID AS VARCHAR) + Location
)

Now you only need to INSERT like this:
INSERT INTO MyTable (Location) VALUES ('PK')

This will give you a row with these values:
ID  Location AccountNo
1   PK       1PK

You could also create a constraint on the computed column to enforce unique values for AccountNo:
ALTER TABLE MyTable
    ADD CONSTRAINT UX_MyTable_AccountNo UNIQUE (AccountNo)


text:
Q: SciLinux: libgfortran.so.3: version 'GFORTRAN_1.4' not found I am beginner in *nix systems, so there may be no sense in my actions :)
I'm trying to make a piece of software, written by our university team, run on a Scientific Linux 6.5. I am getting the whole time this error: "libgfortran.so.3: version `GFORTRAN_1.4' not found". I did a small research and have a small question: am I right, that according to RPM search result, there is no package for SciLinux, that includes GFORTRAN_1.4? I found RPMs with GFORTRAN_1.0 for SciLinux, but no RPMs with GFORTRAN_1.4 on this site:http://rpm.pbone.net
locate libgfortran.so returned:
/usr/lib/gcc/x86_64-redhat-linux/4.4.4/libgfortran.so
/usr/lib/gcc/x86_64-redhat-linux/4.4.4/32/libgfortran.so
/usr/lib64/libgfortran.so.3
/usr/lib64/libgfortran.so.3.0.0

I did objdump -T /usr/lib64/libgfortran.so.3 | grep GFORTRAN_1.4 and it didn't return anything. I tried to update gcc and libgfortran via yum install and it didn't solve the problem.
gcc version 4.4.7 20120313 (Red Hat 4.4.7-4)
So I would appreciate any help on this topic.

A: GFORTRAN_X.Y is the name of a symbol node (google for "symbol versioning" if you wish to know more). For GCC 4.4 the highest version node is GFORTRAN_1.2. For GFORTRAN_1.4 you need GCC 4.6.
In practice, what this means is that you're trying to make some binary compiled on some newer Linux distro work on Scientific Linux 6.5. This is unlikely to work, please recompile the software on SL 6.5.


text:
Q: Bootstrap - Change card style with container width I want to show different views of cards for medium and smaller devices. I need to change the card style according to the width of the container.
For large devices I have this card style:

            Project One

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet numquam aspernatur eum quasi sapiente nesciunt? Voluptatibus sit, repellat sequi itaque deserunt, dolores in, nesciunt, illum tempora ex quae? Nihil, dolorem!

And for medium and small devices I need this:

Project One

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium veniam exercitationem expedita laborum at voluptate. Labore, voluptates totam at aut nemo deserunt rem magni pariatur quos perspiciatis atque eveniet unde.

      View Project

I have no idea how to do this. Can someone suggest the best/most optimized way for accomplishing this?

A: Use Bootstrap Display Property to hide the div in specific screen size.
https://getbootstrap.com/docs/4.0/utilities/display/


text:
Q: IntelliJ on macOS, how do I jump to previously defined bookmark? On IntelliJ mac, is there a way to add a bookmark on the code where we can jump to that piece of code with a shortcut
I can add a bookmark by using F11 or command F11 and give it a number but is there then a shortcut I can use say if i'm somewhere else in that file but want to jump to the bookmark?

A: SHIFT-F11 is the thing you are looking for. Alternatively:
Navigate/Bookmarks/Show Bookmarks


text:
Q: ASP.NET Core 3.1 Routing for Razor Pages How can I configure routing to enable different users to use their own distinct url when accessing the site?  I want to display their logo and other customization upon initial visit.
Something like this:
mysite.com\customer1
mysite.com\customer2

I would much prefer the following, but I believe this is not possible.
customer1.mysite.com
customer2.mysite.com

Is their a better way to achieve this intent?

A: This isn't really a routing concern.
You can have multiple subdomains pointing to the same application, and then use middleware to resolve which domain was used and set values accordingly:
public class DomainResolverMiddleware
{
    private readonly RequestDelegate _next;

    public DomainResolverMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        var host = context.Request.Host.ToString();
        // do whatever
        await _next(context);
    }
}


text:
Q: In Propel2, filter crossref by null value I use Propel2 orm.
I've 2 tables Entry and Category connected by a many-to-many relationship via an EntryCategory table.
I set isCrossRef on true in schema.xml.
Everything works fine : I'm able to filter entry by category like this :
EntryQuery::create()->filterByCategory($cat)

BUT
I'm not able to filter entries with no category. I tried
EntryQuery::create()->filterByCategory(null, Criteria::EQUAL)

or
EntryQuery::create()->filterByCategory(null, Criteria::ISNULL)

but, it gives me
'filterByCategory() only accepts arguments of type \Category or Collection'

I also tried
EntryQuery::create()->where('Category IS NULL')

but, i've got this error
Unknown column 'Category' in 'where clause'

So, I need some help ...
EDIT :
Extract of my schema.xml :
<?xml version="1.0" encoding="utf-8"?>
<database package="core" name="bank" identifierQuoting="true" defaultIdMethod="native" defaultPhpNamingMethod="underscore">

    <column name="id" phpName="Id" type="INTEGER" size="5" primaryKey="true" autoIncrement="true" required="true"/>
    <column name="name" phpName="Name" type="VARCHAR" size="50" required="true"/>
    <column name="parent_id" phpName="ParentId" type="INTEGER" size="5"/>
    <foreign-key foreignTable="category" phpName="Parent">
      <reference local="parent_id" foreign="id"/>
    </foreign-key>
    <index name="parent_id">
      <index-column name="parent_id" size="5"/>
    </index>
    <vendor type="mysql">
      <parameter name="Engine" value="InnoDB"/>
    </vendor>

    <column name="id" phpName="Id" type="INTEGER" primaryKey="true" autoIncrement="true" required="true"/>
    <column name="account_id" phpName="AccountId" type="INTEGER" required="true"/>
    <column name="date" phpName="Date" type="DATE" required="true"/>
    <column name="entry" phpName="Entry" type="VARCHAR" size="255" required="true"/>
    <column name="type" phpName="Type" type="INTEGER" size="2"/>
    <column name="amount" phpName="Amount" type="DECIMAL" size="12" scale="2" required="true"/>
    <index name="account">
      <index-column name="account_id"/>
    </index>
    <index name="md5">
      <index-column name="md5" size="32"/>
    </index>
    <index name="md5_2">
      <index-column name="md5" size="32"/>
      <index-column name="account_id"/>
    </index>
    <foreign-key foreignTable="account">
      <reference local="account_id" foreign="id"/>
    </foreign-key>
    <vendor type="mysql">
      <parameter name="Engine" value="InnoDB"/>
    </vendor>

    <column name="entry_id" phpName="EntryId" type="INTEGER" primaryKey="true" required="true"/>
    <column name="category_id" phpName="CategoryId" type="INTEGER" size="5" primaryKey="true" required="true"/>
    <foreign-key foreignTable="entry" name="entry_category_ibfk_1">
      <reference local="entry_id" foreign="id"/>
    </foreign-key>
    <foreign-key foreignTable="category" name="entry_category_ibfk_2">
      <reference local="category_id" foreign="id"/>
    </foreign-key>
    <index name="category_id">
      <index-column name="category_id" size="5"/>
    </index>
    <vendor type="mysql">
      <parameter name="Engine" value="InnoDB"/>
    </vendor>

</database>

A: You need to use the Id or Name or whatever the column name is.
->filterByCategory expects a propel object of the category type.
->filterByCategoryId() or whatever the name for the actual column is. (having your schema would be beneficial)
Not passing anything sets it up to look for null. Anything else is handled as a string literal.  where column = 'null'

Use either ->filterByCategory() (if that is the name of your column and NOT a foreign key reference) or ->filterByCategoryId() if 'CategoryId' is the 'phpName' of the column.

A: Ok i found 2 solutions (yes, 5 years after ;) )
EntryQuery::create()->leftJoinCategory->where('Category.CategoryId IS NULL')

Or
EntryQuery::create()->useCategoryQuery(null, Criteria::LEFT_JOIN)->filterByCategoryId(null, Criteria::ISNOTNULL)->endUse();


text:
Q: mysql like query on several fields I am trying to do a search query where the search string could be in several fields. This table has > 20K records and the query is taking 6-7 seconds. I am trying to figure a way to speed this up.
SELECT SQL_CALC_FOUND_ROWS cl.fname,
                           cl.email,
                           e.e_id
FROM   clients cl,
       records e
WHERE  (( cl.fname LIKE 'smith%'
           OR cl.lname LIKE 'smith%'
           OR cl.email LIKE 'smith%' ))
       AND cl.id = e.client_id

I was wondering about making one field that had all three text strings and do a fulltext search on one field instead of three.
Any help is appreciated.
Thom

A: You could do something like:
SELECT *
FROM   ((SELECT l.fname,
                cl.email,
                e.e_id
         FROM   clients cl
                JOIN records e
                  ON cl.id = e.client_id
         WHERE  cl.fname LIKE 'smith%')
        UNION ALL
        (SELECT l.fname,
                cl.email,
                e.e_id
         FROM   clients cl
                JOIN records e
                  ON cl.id = e.client_id
         WHERE  cl.lname LIKE 'smith%')
        UNION ALL
        (SELECT l.fname,
                cl.email,
                e.e_id
         FROM   clients cl
                JOIN records e
                  ON cl.id = e.client_id
         WHERE  cl.email LIKE 'smith%')) d
GROUP  BY id;

and you need indexes on the following

*

*(records.client_id)

*(clients.id)

*(clients.fname)

*(clients.lname)

*(clients.email)


text:
Q: Pythagorean triple $(\xi,n,\zeta)$,prove that at least one of the numbers are divisible by $3,5$ Let a Pythagorean triple $(\xi,n,\zeta)$.Prove that at least one of $\xi,n$ is divided by $3$ and that at least one of $\xi,n, \zeta$ is divided by $5$.
That's what I have thought:
We suppose that :
1)$\xi=3n+1 \text{ and } n=3m+1$
2)$\xi=3n+1 \text{ and }n=3m+2$
3) $\xi=3n+2 \text{ and } n=3m+2$
and we show that at no of the above cases it is possible that $\xi^2+n^2=\zeta^2\text{ ,because the remainders will be } 2,8,9, \text{ but  the only possible remainders that can give } n^2,\text{ divided by } 9, \text{ are } 0,1, \text{ so it is a contradicton.}   $
Similarly,we can show that at least one of $\xi,n, \zeta$ must be divisible by $5$.
Is the way I thought right??
Is there also an other way?

A: The only squares modulo three are $0$ and $1$, if neither $\xi$ or $n$ are divisible by $3$ we have $\zeta^2 \equiv 2 \pmod 3$, impossible.
The only squares modulo $5$ are $0,1,-1$ so if none of $\xi,n \zeta$ are divisible by $5$, we have $1+ 1\equiv \pm \zeta^2 \pmod 5$ or $1- 1\equiv \pm \zeta^2 \pmod 5$ also seen to be impossible.


text:
Q: Using IF/ELSE IF/ELSE statements in Attribute Expressions for String Fields I am trying to do build some Attribute Expressions using Arcade and I am having some issues with it returns the else statement. I know that there are features that would return true because I have used these parameters under filters before.
var parksign = $feature.ParkSign2;
var signpole = $feature.SignPole1;

if(parksign == 'One on bus stop pole, 2nd on breakaway in ground, grass, dirt'){
    return 'Yes'
}else if(signpole == 'Yes, Metro breakaway in ground, grass, or dirt'){
    return 'Yes'
}else{
    return 'No'
}

A: After halfway completing this post yesterday I ended up finding the answer. The fields that I was attempting to use logical statements on were configured with Domains or a List of Values. When you configure using these fields everywhere else in the platform the domain alias is displayed in the filter or function, but when you configure using Arcade or Attribute Expressions $feature.SignPole1 is looking for the Domain Code. If you want to look at the Name/Label you have to use DomainName($feature.SignPole1).
For assistance you can reference you can look at the feature class information > data > fields > list of values.
OR
Under the Attribute Expressions panel globals > $feature > find you data column


text:
Q: Playing a .mov file without UIWebView or MPMoviePlayer I am trying to play a video file with the .mov extension. It is not playing the video in my MPMoviePlayerController.  I need to play this type of file in my application. Is it possible to play a video file without using MPMoviePlayerController or UIWebView?
Please anyone suggest me in this issue.
Thanks in Advance

A: I've never used it directly before, but take a look at the AVPlayer Class Reference.
Under the "Overview", you'll see:

You use an AVPlayer object to implement controllers and user
  interfaces for single- or multiple-item playback. The multiple-item
  case supports advanced behaviors.

If you look at the AV Foundation Programming guide (linked here), you'll see Apple builds the Media Player upon AV foundation.


text:
Q: Задать уровень логгирования в Monolog извне? Возьмем пример из документации Monolog:
?php

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));

// add records to the log
$log->warning('Foo');
$log->error('Bar');

Вопрос: как задать уровень логгирования (WARNING в Logger::WARNING) из переменной (например, $log_level='WARNING')?

A: Logger:WARNING просто константа. Константу можно сохранить в переменную и использовать позже.
$log_level = Logger::WARNING
// create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', $log_level));

Если нужно именно из строки то проще всего использовать словарь.
$log_level = 'warning';
$possible_levels = ['debug' => Logger::DEBUG,
                    'info' => Logger::INFO,
                    'warning' => Logger::WARNING, /*other levels */];

$level = $possible_levels[ $log_level ];
$log = new Logger( 'name' );
$log->pushHandler( new StreamHandler( 'path/to/your.log', $level ) );

Если нехочется заводить словарь или хочется избежать дублирования уровней, то можно использовать рефлексию
$log_level = 'WARNING';
$LoggerRef = new \ReflectionClass( 'Monolog\Logger' );
$level = $LoggerRef->getConstant( $log_level );
$log = new Logger( 'name' );
$log->pushHandler( new StreamHandler( 'path/to/your.log', $level )


text:
Q: Comment code with /**/? I'm using visual studio 2010 , (with resharper installed if it helps) :
is there any shortcut of commenting a code via /* lalala */ and not via //lalala ?
I already know that CTRL K C comment a code but it comments it with //
Is there anyway of commenting a code via /**/ ?

A: There is ReSharper | Edit | Comment with block comment which makes exactly what you need.
Default shortcut for this - Ctrl+Shift+/
If you would like to uncomment it, put the caret on any place in the comment and hit Ctrl+Shift+/ once again. The same behavior is available for ReSharper | Edit | Comment with line comment (Ctrl+Alt+/) as well.

A: If you only select lalala and then hit CTRL K + C, it will uncomment lalala with /* */ (for example when lalala is a parameter in a function, just double click it and hit CTRL K+C.

A: Found it in resharper :
you can add :


text:
Q: Can i hide the line "powered by instamojo"? I create a payment link using instamojo. But when it is loading it shows a line  "powered by instamojo" at the bottom of the payment link. Is there anyway to hide that text?

A: Yes, it is possible to hide this line by using this app:
https://www.instamojo.com/apps/details/com.instamojo.remove_branding/
(This link is only accessible when you're logged into your Instamojo account)

A: You don't need to use any app or pay anything to remove it. If you are a developer , you can remove it simply by downloading the im-embed.min.js script and comment out the line below
function o(e) {
    return true;
    // c(e).parent(".im-checkout").append('Powered by Instamojo')
}

A: Yes , exactly as a developer we don't need to work on any instamojo app as such , all we need to do is
extract this link from the script file what instamojo guys provide https://d2xwmjc4uy2hr5.cloudfront.net/im-embed/im-embed.min.js by loading this link in browser the script file  "im-embed.min.js" will be downloaded , after that you can copy this file to your local folder and start making changes as per your requirement, in the developer console
similary you can work on stylesheet by extracting the link from im-embed.min.js


text:
Q: find views that are using a certain table How to find all views that select from this table it is possible in oracle using this query is there anything the same in psql
SELECT name ,
type ,
referenced_name ,
referenced_type
FROM user_dependencies
WHERE TYPE   = 'VIEW'
AND NAME = '<VIEW_NAME>'
AND referenced_type = '<TABLE_NAME'>;

A: This query lists all views that are using table table_name (including views that are using views that are using the table, etc):
select distinct n.nspname as schema_name, c.relname as view_name
from pg_depend d
join pg_rewrite w on w.oid = d.objid
join pg_class c on c.oid = w.ev_class
join pg_namespace n on n.oid = c.relnamespace
where d.refclassid = 'pg_class'::regclass
and d.classid = 'pg_rewrite'::regclass
and d.refobjid = 'table_name'::regclass
and c.oid <> 'table_name'::regclass

A: select * from pg_views where lower(definition) like lower('%<TABLE_NAME>%');

would that fit?..

A: Found a solution if someone is looking for it.
SELECT table_name from INFORMATION_SCHEMA.table_views
where table_name = '<table_name>'

and to get more information about the view you can then use the INFORMATION_SCHEMA.views and join it with table_viewson view_name from views and table_name from views.

A: select table_name view_name
from information_schema.views
where view_definition ilike '%table_name%' and
table_schema = 'public' and table_catalog='db_name'


text:
Q: Cannot update plugin for WordPress on localhost on Mac I'm running WordPress 5.8.1 on localhost, on my Mac. I am unable to update plugins. I get this error:
Update failed: Could not create directory.
I've tried changing the permission on the wp-content folder as suggested here like this:
sudo chmod -R 755 wp-content

but it didn't work. I still get the error message.
I also tried this
sudo chown -R _www wp-dir
sudo chmod -R g+w wp-dir

still no luck.

A: Ok, Managed to find the issue. Apache uses a different username so this command was ok:
sudo chown -R _www wp-dir

But my username wasn't _www (hence my error)
you can find the apache username in the etc/httpd.conf file


text:
Q: Assign a variable in hyperlink using ASP.Net MVC I have defined a variable :
    <%int imageTypSelected = 0; %>

And I have these :

         <img src='<%: Url.Action("getImg", "Pr", new{Id = Model.Id}) %>'   alt="" />
         A

         <img src='<%: Url.Action("getImg_Alt1", "Pr", new{Id = Model.Id}) %>'   alt="" />
         B

         <img src='<%: Url.Action("getImg_Alt2", "Pr", new{Id = Model.Id}) %>'   alt="" />
         C

Now I want that when the user select the first hyperlink "1" assigns to the variable.
for second hyperlink "2" and for the last "3". But how? this variable will be post to a method in controller later. How can I have this assignment?

A: You need to pass the value from the controller back into your view; either make it a part of your model, or add it to the ViewBag. You can then assign it like this:
<% int imageTypSelected = Model.ImageTypeSelected; %>

...or like this:
<% int imageTypSelected = (int)ViewBag.ImageTypeSelected; %>


text:
Q: Trying to get my program to display the original Matrices I am relatively new to C++ and I have an assignment that is making perform mathematical operations with matrices. I was able to complete the operations but I can't seem to display the original matrices I inputted into the output with out doing a "cout" command for each number. I'm trying to display the original matrices before the answer to the 5 questions.
This is what I have done:
#include <stdio.h>
#include <iostream>
using namespace std;
void matrix(int A[3][3], int B[3][3], int result[3][3])
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            for (int k = 0; k < 3; k++)
                result[i][j] += (A[i][k] * B[k][j]);
        }
    }
}
void scalar(int A[3][3], int num, int result[3][3])
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            result[i][j] = A[i][j] * num;
        }
    }
}
void display(int result[3][3])
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
            cout << result[i][j] << ",";
        cout << endl;
        ;

    }
}
int main()
{
    //inputting matrix values
    int A[3][3]={{13,9,7},{8,7,4},{6,4,0}};
    int B[3][3]={{1,3,5},{6,2,-3},{2,0,4}};
    int C[3][3]={{1,0,0},{0,1,0},{0,0,1}};
    int result[3][3]={{0,0,0},{0,0,0},{0,0,0}};

    //question 1
    matrix(A,B,result);
    cout<<"A * B ="<<endl;
    display(result);
    int result0[3][3]={{0,0,0},{0,0,0},{0,0,0}};

    //question 2
    matrix(B,A,result0);
    cout<<"B * A ="<<endl;
    display(result0);
    int result1[3][3]={{0,0,0},{0,0,0},{0,0,0}};

    //question 3
    matrix(C,B,result1);
    cout<<"C * B ="<<endl;
    display(result1);
    int result2[3][3]={{0,0,0},{0,0,0},{0,0,0}};

    //question 4
    scalar(A,2,result2);
    cout<<"2 * A ="<<endl;
    display(result2);
    int result3[3][3]={{0,0,0},{0,0,0},{0,0,0}};

    //question 5
    scalar(B,-4,result3);
    cout<<"-4 * B ="<<endl;
    display(result3);
    return 0;

}


text:
Q: Confusion over apk resource files and internal/external files in Android I am writing an app that has a HorizontalSrollView composed of a LinearLayout that is composed of ImageViews.
I have default images for the HorizontalScrollView in the res/drawable folder. These images should check against a list of images on a server somewhere and if the files are different, the new ones should download and other files that doesn't exist on the file but on the device should be removed.
All that works, except for during my debugging process I have a question. Every time I click "run" on eclipse, does the internal and external storage of my app get removed clean or do the files stay there even if I am installing a newer "version" of my app?


text:
Q: Add an Order column to an existing table that contains data with SQL query Recently I was working on a project that needs to add a column to sort existing records. To clarify the subject, I will give a small example. Suppose we have a table to store the names of Corona vaccine injection centers and another table to register the people who come to each of these centers. After collecting the data, we come to the conclusion that to manage the order of turns, we must add a "Order" column to Person table. How can I do this by writing a query without losing the data collected so far?
Here is the table of centers:

And this is the table of person:

And what I expect is something like this:

PS: I use SQL to create tables and store data.

A: select Id,
       Name,
       CenterID,ROW_NUMBER() over (partition by CenterId order by Id) as Order
from person

A: I would create a view for this with the Order column created on the fly.
Is it an order or a sequence? I'd avoid "order" as it's a reserved word.
Create view PersonSequence as

Select Id, Name, CentreId,
  row_number() over (partition by CentreId order by Id) as Sequence
from Person

To update an existing table you could do
alter table Person add Seq int;

with u as (
  Select *,
  row_number() over (partition by CentreId order by Id) as rn
  from Person
)
update u
set seq=rn;

See Fiddle Example


text:
Q: Facing issue while creating user in openfire I have following simple code which works when I don't have dependency
AuthenticationToken authenticationToken = new AuthenticationToken("admin", "password");
        RestApiClient restApiClient = new RestApiClient("http://192.168.20.97", 7070, authenticationToken);
        UserEntity userEntity = new UserEntity("dasddasd","dsadsadasd", "", "password");
        restApiClient.createUser(userEntity);

<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-client</artifactId>
    <version>3.1.4.Final</version>
</dependency>

And when I add above dependency it throws following error
Exception in thread "main" javax.ws.rs.ProcessingException: RESTEASY004655: Unable to invoke request
    at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:316)
    at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:462)
    at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:498)
    at org.jboss.resteasy.client.jaxrs.internal.ClientInvocationBuilder.method(ClientInvocationBuilder.java:295)
    at org.igniterealtime.restclient.RestClient.call(RestClient.java:145)
    at org.igniterealtime.restclient.RestClient.post(RestClient.java:91)
    at org.igniterealtime.restclient.RestApiClient.createUser(RestApiClient.java:92)
    at app.Test.main(Test.java:20)
Caused by: javax.ws.rs.ProcessingException: RESTEASY003215: could not find writer for content-type application/xml type: org.igniterealtime.restclient.entity.UserEntity
    at org.jboss.resteasy.core.interception.jaxrs.ClientWriterInterceptorContext.throwWriterNotFoundException(ClientWriterInterceptorContext.java:40)
    at org.jboss.resteasy.core.interception.jaxrs.AbstractWriterInterceptorContext.getWriter(AbstractWriterInterceptorContext.java:146)
    at org.jboss.resteasy.core.interception.jaxrs.AbstractWriterInterceptorContext.proceed(AbstractWriterInterceptorContext.java:121)
    at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.writeRequestBody(ClientInvocation.java:390)
    at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.writeRequestBodyToOutputStream(ApacheHttpClient4Engine.java:630)
    at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.buildEntity(ApacheHttpClient4Engine.java:595)
    at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.loadHttpMethod(ApacheHttpClient4Engine.java:483)
    at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:305)
    ... 7 more

I need above dependency for creating user in Keycloak

A: You probably just have to add the following dependency in order to get a the jackson framework integrated. It will marshal/unmarshal JSON and XML automatically.
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jackson2-provider</artifactId>
    <version>3.1.4.Final</version>
</dependency>

A: Ultimately the issue is XML vs JSON.  If you look at the source to RestClient which is used by RestApiClient it always sends in XML.  Keycloak is always JSON and so it won't be able to talk XML.
It looks like you can set the Accepts header by using RestClientBuilder but the Content-Type is hard coded.


text:
Q: Powershell create scriptblock for Func instead of Action I have a class I'm attempting to use from Powershell. This class has a method, called Execute(), with two overloads: one which takes a Func<T> and one which takes an Action<T>. I can call the overload that takes an Action<T> using a scriptblock as the delegate, but I cannot figure out how to call the overload that takes a Func<T>:
add-type -TypeDefinition @'
using System;

public class DelegTest
{
    public R Execute<R>(Func<R> method)
    {
        return method();
    }

    public void Execute(Action method)
    {
        Execute(() => { method(); return true; });
    }
}
'@

$t = new-object DelegTest
$t.Execute({ 1 + 1 }) # returns nothing

How do I call the overload that takes a Func<T>? I assume this would require creating a ScriptBlock that has a return type, but I don't know how to do this; the Powershell parser apparently isn't smart enough to do this automatically.

A: You need to cast ScriptBlock to right delegate type by yourself:
$t.Execute([Func[int]]{ 1 + 1 })


text:
Q: Apache IP Virtual Hosts Server has two IPs, fresh centos min install. Apache is working, both ips load Apache test page. both www.domain.com and domain.com resolve to second IP.
I'd like for the first IP (192.168.0.1) to load Apache test page, this is working fine
I want the second IP (192.168.0.2) to load a website in /home/site/www
Currently when we goto domain.com or www.domain.com or 2nd IP it loads apache test page instead of the site, here's our config. Also I have the IPs listed as 192 instead of the real ips. What am I missing? Why isn't 192.168.0.2 loading /home/site/www instead of the Apache test page?
ServerRoot "/etc/httpd"
Listen 80
ServerName 192.168.0.1:80
DocumentRoot "/var/www/html"
<Directory "/var/www/html">

NameVirtualHost 192.168.0.2:80

<VirtualHost 192.168.0.2:80>
DocumentRoot /home/site/www
ServerName mydomain.com
ServerAlias *.mydomain.com
ErrorLog logs/mydomain.com-error_log
CustomLog logs/mydomain.com-access_log common
</VirtualHost>

Update
The Fix
chcon -R --reference=/var/www /home/site/www
SELinux needed the correct permissions set on it, using the reference it copies the same permissions to my new folder

A: Try this:
ServerRoot "/etc/httpd"
Listen 80
ServerName 192.168.0.1:80

NameVirtualHost 192.168.0.1:80
NameVirtualHost 192.168.0.2:80

<VirtualHost 192.168.0.1:80>
DocumentRoot /var/www/html
ServerName mydomain.com  #change accordingly
ServerAlias *.mydomain.com
ErrorLog logs/mydomain.com-error_log
CustomLog logs/mydomain.com-access_log common
</VirtualHost>

<VirtualHost 192.168.0.2:80>
DocumentRoot /home/site/www
ServerName mydomain2.com
ServerAlias *.mydomain2.com
ErrorLog logs/mydomain2.com-error_log
CustomLog logs/mydomain2.com-access_log common
</VirtualHost>

Don't forget to apply the changes on apache.
service httpd reload or similar command.
Also, make sure the directory /var/www/html has, at least, reading permissions for the apache user.

A: You are missing the  NameVirtualHost  directive.
  NameVirtualHost 192.168.0.2:80

I would also highly suggest putting in Directory directives in as well.


text:
Q: finish() method in android closing the entire application In my MainScreen.java class I am calling startActivityForResult() method when I am clicking on a image:
case R.id.add_device_btn:
case R.id.add_device_btn_text:
    startActivityForResult(new Intent(MainScreen.this, DeviceDiscovery.class), REQUEST_DISCOVERY);
    break;

In my DeviceDiscovery class I wrote this code when I am clicking on the list Item
@Override
protected void onListItemClick(ListView lv, View view, int position, long id) {
    super.onListItemClick(lv, view, position, id);
    // since user selected already a device we do not need to scan for more devices
    localDevice.stopScan();

    final String address = ((RemoteDevice)adapter.getItem(position)).getAddress();
    Intent i = new Intent();
    i.putExtra(ADDRESS_EXTRA, address);
    setResult(RESULT_OK, i);
    finish();
}

I did this because when I click on the list it should come to the onActivityResult() method.
But now when I click on the list item the entire application get closed, the control is not going to that onActivityResult() method.
So how to fix this problem?
onActivityResult() method
      @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode){
    case REQUEST_DISCOVERY:
        if (resultCode == RESULT_OK){
            String address = data.getStringExtra(DeviceDiscovery.ADDRESS_EXTRA);
            // add only if device is not already in the list
            if (!devices.deviceEntries.contains(new BTDevice(address))){
                db.open();
                db.createDevice(new BTDevice(LocalDevice.getInstance().getRemoteForAddr(address)));
                devices.deviceEntries = db.fetchAllDevices();
                db.close();
                devices.notifyDataSetChanged();
            }
            else {
                Logger.d(TAG, "Duplicate entry: device already added");
                Toast.makeText(this, "Selected device is already in your list", Toast.LENGTH_SHORT).show();
            }
        }
        break;
    }
}

this is my MainScreen class
    public class MainScreen extends ListActivity implements OnClickListener{

public static final int REQUEST_DISCOVERY = 2;

private static final int MENU_ITEM_SHOW_EVENTS = 1;
private static final int MENU_ITEM_CONNECT = 2;
private static final int MENU_ITEM_REMOVE_DEVICE = 3;
private static final int MENU_ITEM_MOVE_UP = 4;
private static final int MENU_ITEM_MOVE_DOWN = 5;

private static final int MENU_ABOUT = 10;

private static final int DIALOG_ABOUT = 1;

AmarinoDbAdapter db;
DeviceListAdapter devices;

boolean isBound = false;
MyHandler handler = new MyHandler();

BroadcastReceiver receiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        if (action == null) return;
        Logger.d(TAG, action + " received");

        if (AmarinoIntent.ACTION_CONNECTED_DEVICES.equals(action)){
            updateDeviceStates(intent.getStringArrayExtra(AmarinoIntent.EXTRA_CONNECTED_DEVICE_ADDRESSES));
            return;
        }

        final String address = intent.getStringExtra(AmarinoIntent.EXTRA_DEVICE_ADDRESS);
        if (address == null) return;

        Message msg = new Message();

        if (AmarinoIntent.ACTION_CONNECTED.equals(action)){
            msg.what = MyHandler.CONNECTED;
        }
        else if (AmarinoIntent.ACTION_DISCONNECTED.equals(action)){
            msg.what = MyHandler.DISCONNECTED;
        }
        else if (AmarinoIntent.ACTION_CONNECTION_FAILED.equals(action)){
            msg.what = MyHandler.CONNECTION_FAILED;
        }
        else if (AmarinoIntent.ACTION_PAIRING_REQUESTED.equals(action)){
            msg.what = MyHandler.PAIRING_REQUESTED;
        }
        else return;

        msg.obj = address;
        handler.sendMessage(msg);
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Logger.d(TAG, "onCreate");
    setContentView(R.layout.main);

    findViewById(R.id.add_device_btn).setOnClickListener(this);
    findViewById(R.id.add_device_btn_text).setOnClickListener(this);

    findViewById(R.id.monitoring_btn).setOnClickListener(this);
    findViewById(R.id.monitoring_btn_text).setOnClickListener(this);

    findViewById(R.id.settings_btn).setOnClickListener(this);
    findViewById(R.id.settings_btn_text).setOnClickListener(this);

    /* Since the settings button is not used so far, I hide it */
    findViewById(R.id.settings_btn_layout).setVisibility(View.GONE);

    db = new AmarinoDbAdapter(this);
    db.open();
    devices = new DeviceListAdapter(this, db.fetchAllDevices());
    db.close();

    setListAdapter(devices);
    registerForContextMenu(getListView());

    showReleaseNotes();
}

private void showReleaseNotes() {
    SharedPreferences prefs = getPreferences(MODE_PRIVATE);
    int versionCode = getVersionCode();
    if (prefs.getInt(PREF_VERSION, 0) != versionCode){
        showDialog(DIALOG_ABOUT);
        prefs.edit().putInt(PREF_VERSION, versionCode).commit();
    }
}

@Override
protected void onStart() {
    super.onStart();
}

@Override
protected void onResume() {
    super.onResume();
    // listen for device state changes
    IntentFilter intentFilter = new IntentFilter(AmarinoIntent.ACTION_CONNECTED_DEVICES);
    //intentFilter.addAction(AmarinoIntent.ACTION_CONNECTED);
    //intentFilter.addAction(AmarinoIntent.ACTION_DISCONNECTED);
    intentFilter.addAction(AmarinoIntent.ACTION_CONNECTION_FAILED);
    intentFilter.addAction(AmarinoIntent.ACTION_PAIRING_REQUESTED);
    registerReceiver(receiver, intentFilter);

    // request state of devices
    Intent intent = new Intent(this, AmarinoService.class);
    intent.setAction(AmarinoIntent.ACTION_GET_CONNECTED_DEVICES);
    startService(intent);
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(receiver);
}

@Override
protected void onStop() {
    super.onStop();
}

@Override
protected void onDestroy() {
    super.onDestroy();
}

private void updateDeviceStates(String[] connectedDevices){
    if (connectedDevices == null) {
        Logger.d(TAG, "no connected devices");
        for (BTDevice device : devices.deviceEntries){
            Message msg = new Message();
            msg.what = MyHandler.DISCONNECTED;
            msg.obj = device.address;
            handler.sendMessage(msg);
        }
        return;
    }

    Logger.d(TAG, "connected devices detected: " + connectedDevices.length);
    for (BTDevice device : devices.deviceEntries){
        boolean connected = false;
        Message msg = new Message();
        // this is normally a very short list, not matter that this is in O(n^2)
        for (int i=0; i<connectedDevices.length; i++){
            if (connectedDevices[i].equals(device.address)){
                msg.what = MyHandler.CONNECTED;
                connected = true;
                break;
            }
        }
        if (!connected){
            msg.what = MyHandler.DISCONNECTED;
        }
        msg.obj = device.address;
        handler.sendMessage(msg);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(Menu.NONE, MENU_ABOUT, Menu.FIRST, R.string.menu_about)
        .setIcon(R.drawable.about_icon);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
    case MENU_ABOUT:
        showDialog(DIALOG_ABOUT);
    }
    return super.onOptionsItemSelected(item);

}

@Override
protected Dialog onCreateDialog(int id) {
    Dialog dialog;
    switch(id) {
        case DIALOG_ABOUT:
            dialog = getAboutBox();
            break;

        default:
            dialog = null;
    }
    return dialog;
}

private AlertDialog getAboutBox() {
    String title = getString(R.string.app_name) + " build " + getVersion(this);

    return new AlertDialog.Builder(MainScreen.this)
        .setTitle(title)
        .setView(View.inflate(this, R.layout.about, null))
        .setIcon(R.drawable.icon_small)
        .setPositiveButton("OK", null)
        .create();

}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    // Setup the menu header
    AdapterView.AdapterContextMenuInfo info;
    info = (AdapterView.AdapterContextMenuInfo) menuInfo;
    BTDevice device = devices.deviceEntries.get(info.position);
    menu.setHeaderTitle(device.name);

    menu.add(0, MENU_ITEM_CONNECT, 0,
            device.state == AmarinoIntent.DISCONNECTED ? R.string.connect : R.string.disconnect);
    menu.add(0, MENU_ITEM_SHOW_EVENTS, 0, R.string.show_events);
    menu.add(0, MENU_ITEM_REMOVE_DEVICE, 0, R.string.remove_device);

    //menu.add(0, MENU_ITEM_MOVE_UP, 0, "Move up");
    //menu.add(0, MENU_ITEM_MOVE_DOWN, 0, "Move down");

}

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info;
    info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    BTDevice device = devices.deviceEntries.get(info.position);

    switch (item.getItemId()) {
    case MENU_ITEM_REMOVE_DEVICE:
        // before we remove the device, we disconnect it if connected
        if (device.state == AmarinoIntent.CONNECTED){
            Toast.makeText(this, "Please disconnect the device before removing it!", Toast.LENGTH_SHORT).show();
        }
        else {
            db.open();
            db.deleteDevice(device.id);
            devices.deviceEntries = db.fetchAllDevices();
            db.close();
            devices.notifyDataSetChanged();
        }

        return true;
    case MENU_ITEM_SHOW_EVENTS:
        onEventListBtnClick(info.position);
        return true;
    case MENU_ITEM_CONNECT:
        Button btn = (Button) info.targetView.findViewById(R.id.connect_btn);
        onConnectBtnClick(btn, info.position);
        return true;
    case MENU_ITEM_MOVE_UP:
        // TODO move this selected device one position up
        return true;
    case MENU_ITEM_MOVE_DOWN:
        // TODO move this selected device one position down
        return true;
    }
    return false;
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    openContextMenu(v);
}

@Override
public void onClick(View v) {
    switch(v.getId()){
        case R.id.connect_btn:
            Button btn = (Button)v;
            int postion = (Integer) v.getTag();
            onConnectBtnClick(btn, postion);
            break;

        case R.id.list_btn:
            int pos = (Integer) v.getTag();
            onEventListBtnClick(pos);
            break;

        case R.id.add_device_btn:
        case R.id.add_device_btn_text:
            Intent obj=new Intent(MainScreen.this,DeviceDiscovery.class);
            //getParent().
            startActivityForResult(obj,1001);
            break;

        case R.id.monitoring_btn:
        case R.id.monitoring_btn_text:
            startActivity(new Intent(MainScreen.this, Monitoring.class));
            break;

        case R.id.settings_btn:
        case R.id.settings_btn_text:
            // TODO Perhaps we need a settings button in the future
            Toast.makeText(this, "not implemented yet", Toast.LENGTH_SHORT).show();
            break;
    }
}

private void onConnectBtnClick(Button btn, int postion) {
    Intent i = new Intent(MainScreen.this, AmarinoService.class);
    i.putExtra(AmarinoIntent.EXTRA_DEVICE_ADDRESS, devices.deviceEntries.get(postion).address);

    if ( btn.getText().equals(getString(R.string.connect)) )
        i.setAction(AmarinoIntent.ACTION_CONNECT);
    else
        i.setAction(AmarinoIntent.ACTION_DISCONNECT);

    btn.setEnabled(false);
    btn.setText(R.string.connecting);

    startService(i);
}

private void onEventListBtnClick(int pos){
    Intent intent = new Intent(MainScreen.this, EventListActivity.class);
    intent.putExtra(AmarinoIntent.EXTRA_DEVICE, devices.deviceEntries.get(pos));
    startActivity(intent);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Toast.makeText(getApplicationContext(), "In mAIn", Toast.LENGTH_SHORT).show();
    //super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode){
    case 1001:
        if (resultCode == RESULT_OK){
            String address = data.getStringExtra(DeviceDiscovery.ADDRESS_EXTRA);
            // add only if device is not already in the list
            if (!devices.deviceEntries.contains(new BTDevice(address))){
                db.open();
                db.createDevice(new BTDevice(LocalDevice.getInstance().getRemoteForAddr(address)));
                devices.deviceEntries = db.fetchAllDevices();
                db.close();
                devices.notifyDataSetChanged();
            }
            else {
                Logger.d(TAG, "Duplicate entry: device already added");
                Toast.makeText(this, "Selected device is already in your list", Toast.LENGTH_SHORT).show();
            }
        }
        break;
    }
}

private class MyHandler extends Handler {

    protected static final int CONNECTED = 1;
    protected static final int DISCONNECTED = 2;
    protected static final int CONNECTION_FAILED = 3;
    protected static final int PAIRING_REQUESTED = 4;

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        final int what = msg.what;
        final String address = (String)msg.obj;

        for (int i=0; i<devices.getCount();i++){
            BTDevice device = (BTDevice)devices.getItem(i);

            if (address.equals(device.address)){
                View view = getListView().getChildAt(i);
                Button btn = (Button)view.findViewById(R.id.connect_btn);
                btn.setEnabled(true);

                switch (what) {
                    case CONNECTED:
                        setDeviceConnected(device, view, btn);
                        break;
                    case CONNECTION_FAILED:
                        Toast.makeText(MainScreen.this, "Connection failed!", Toast.LENGTH_SHORT).show();
                    case DISCONNECTED:
                        setDeviceDisconnected(device, view, btn);
                        break;
                    case PAIRING_REQUESTED:
                        Toast.makeText(MainScreen.this,
                                "Device is not paired!\n\nPlease pull-down the notification bar to pair your device.\n\n", Toast.LENGTH_LONG).show();
                        setDeviceDisconnected(device, view, btn);
                        break;
                }
                view.invalidate();
            }
        } // end for

    } // end handleMessage()

    private void setDeviceConnected(BTDevice device, View view, Button btn) {
        device.state = AmarinoIntent.CONNECTED;
        view.findViewById(R.id.connected).setBackgroundResource(R.color.connected_on);
        view.findViewById(R.id.disconnected).setBackgroundResource(R.color.disconnected_off);
        btn.setText(R.string.disconnect);
    }

    private void setDeviceDisconnected(BTDevice device, View view, Button btn) {
        device.state = AmarinoIntent.DISCONNECTED;
        view.findViewById(R.id.connected).setBackgroundResource(R.color.connected_off);
        view.findViewById(R.id.disconnected).setBackgroundResource(R.color.disconnected_on);
        btn.setText(R.string.connect);
    }

}

public static String getVersion(Context context) {
    String version = "1.0";
    try {
        PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        version = pi.versionName;
    } catch (PackageManager.NameNotFoundException e) {
        Log.e(TAG, "Package name not found", e);
    }
    return version;
}

private int getVersionCode() {
    int code = 1;
    try {
        PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
        code = pi.versionCode;
    } catch (PackageManager.NameNotFoundException e) {
        Log.e(TAG, "Package name not found", e);
    }
    return code;
}

private class DeviceListAdapter extends BaseAdapter {

    ArrayList<BTDevice> deviceEntries;
    Context context;

    @SuppressWarnings("unused")
    public DeviceListAdapter(Context context){
        this.context = context;
    }

    public DeviceListAdapter(Context context, ArrayList<BTDevice> deviceEntries){
        this.context = context;
        this.deviceEntries = deviceEntries;
    }

    public int getCount() {
        if (deviceEntries != null) {
            return deviceEntries.size();
        }
        return 0;
    }

    public Object getItem(int position) {
        return deviceEntries.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        LinearLayout view = null;
        BTDevice device = deviceEntries.get(position);

        if (convertView == null) {
            view = new LinearLayout(context);
            LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            vi.inflate(R.layout.devices_list_item, view, true);
        } else {
            view = (LinearLayout) convertView;
        }

        TextView name = (TextView) view.findViewById(R.id.device_name);
        TextView address = (TextView) view.findViewById(R.id.device_address);
        Button eventListBtn = (Button) view.findViewById(R.id.list_btn);
        Button connectBtn = (Button) view.findViewById(R.id.connect_btn);

        // lets remember which address is associated with our buttons
        connectBtn.setTag(position);
        eventListBtn.setTag(position);

        connectBtn.setOnClickListener(MainScreen.this);
        eventListBtn.setOnClickListener(MainScreen.this);

        name.setText((name==null) ? "NONAME" : device.name);
        address.setText(device.address);

        return view;
    }

}

}
This my DeviceDiscovery class
     public class DeviceDiscovery extends ListActivity {

protected static String ADDRESS_EXTRA = "device_address";
public static final int REQUEST_DISCOVERY = 2;

@SuppressWarnings("unused")
private static final String TAG = "DeviceDiscovery";

private DeviceAdapter adapter;
private LocalDevice localDevice;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitle("Discovered Devices");
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.discovered_devices_list);

    adapter = new DeviceAdapter();
    setListAdapter(adapter);

    setProgressBarIndeterminateVisibility(true);
    localDevice = LocalDevice.getInstance();
}

@Override
protected void onStart() {
    super.onStart();

    localDevice.init(this, new ReadyListener(){

        @Override
        public void ready() {
            localDevice.scan(new ScanListener(){

                @Override
                public void deviceFound(RemoteDevice device) {

                    synchronized(adapter.discoveredDevices){
                        Vector<RemoteDevice> addedDevices = adapter.discoveredDevices;
                        for (RemoteDevice rd : addedDevices){
                            if (rd.getAddress().equals(device.getAddress())){
                                Log.d(TAG, "device already in list -> renew");
                                adapter.discoveredDevices.remove(rd);
                            }
                        }
                        adapter.discoveredDevices.add(device);
                    }
                    adapter.notifyDataSetChanged();
                }

                @Override
                public void scanCompleted() {
                    setProgressBarIndeterminateVisibility(false);
                }
            });
        } // end ready()
    });

}

@Override
protected void onStop() {
    super.onStop();
    // TODO change source of AndroidBluetoothLibrary to fix the bug
    // this might run in an exception, because of a race condition
    // see issue 22 at http://code.google.com/p/android-bluetooth/issues/detail?id=22
    localDevice.destroy();
}

@Override
protected void onListItemClick(ListView lv, View view, int position, long id) {
    super.onListItemClick(lv, view, position, id);
    // since user selected already a device we do not need to scan for more devices
    localDevice.stopScan();

    final String address = ((RemoteDevice)adapter.getItem(position)).getAddress();
    Intent i = new Intent();
    i.putExtra(ADDRESS_EXTRA, address);
    setResult(RESULT_OK, i);
    finish();
}

@Override
protected void onDestroy() {

    // TODO Auto-generated method stub

}

private class DeviceAdapter extends BaseAdapter {

    Vector<RemoteDevice> discoveredDevices = new Vector<RemoteDevice>();

    public int getCount() {
        if (discoveredDevices != null) {
            return discoveredDevices.size();
        }
        return 0;
    }

    public Object getItem(int position) {
        return discoveredDevices.get(position);
    }

    public long getItemId(int position) {
        return 0;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        LinearLayout view = null;

        if (convertView == null) {
            view = new LinearLayout(DeviceDiscovery.this);
            String inflater = Context.LAYOUT_INFLATER_SERVICE;
            LayoutInflater vi = (LayoutInflater) DeviceDiscovery.this.getSystemService(inflater);
            vi.inflate(R.layout.discovered_devices_list_item, view, true);
        } else {
            view = (LinearLayout) convertView;
        }

        TextView addressTextView = (TextView) view.findViewById(R.id.device_address);
        TextView nameTextView = (TextView) view.findViewById(R.id.device_name);

        RemoteDevice device = discoveredDevices.get(position);
        String address = device.getAddress();
        String name = device.getFriendlyName();

        addressTextView.setText(address);
        nameTextView.setText((name==null) ? "NONAME" : name);

        return view;
    }
}

}
Still I can't find the solution , Its still closing the entire application and its not going to that onActivityResult() method also

A: I got the answer,
Its like I forgot to remove the
    android:noHistory="true"

from the manifest.xml file, now I removed this and its  working fine now.
Thanks to all for your reply.


text:
Q: Change proxy after starting chromedriver in java selenium Is it possible to use proxy after starting chromedriver on the same browser?
EX:

*

*I start chrome driver

*Load website

*Put in info

*Use proxy

*Click submit

I think i found some ways to do it in python and JS but im not sure how to convert it to java

A: As per Selenium's current implementation once you configure the WebDriver instance with the required Options and Capabilities and initialize the WebDriver session to open a Web Browser, you cannot change the capabilities runtime. Even if you are able to retrieve the runtime capabilities still you won't be able to change them back.
So, in-order to use a proxy you have to initiate a new WebDriver session.
here is @JimEvans clear and concise comment (as of Oct 24 '13 at 13:02) related to proxy settings capability:

When you set a proxy for any given driver, it is set only at the time WebDriver session is created; it cannot be changed at runtime. Even if you get the capabilities of the created session, you won't be able to change it. So the answer is, no, you must start a new session if you want to use different proxy settings.

You can find a relevant discussion in Set capability on already running selenium webdriver

A: You can use ChromeOptions class.
You can create an instance of ChromeOptions, which has convenient methods for setting ChromeDriver-specific capabilities. You can then pass the ChromeOptions

object into the ChromeDriver constructor:
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File("/path/to/extension.crx"));
ChromeDriver driver = new ChromeDriver(options);

ChromeOptions options = new ChromeOptions();
// Add the WebDriver proxy capability.
Proxy proxy = new Proxy();
proxy.setHttpProxy("myhttpproxy:3337");
options.setCapability("proxy", proxy);

// Add a ChromeDriver-specific capability.
options.addExtensions(new File("/path/to/extension.crx"));
ChromeDriver driver = new ChromeDriver(options);


text:
Q: Show that a $C^2$-function $u$ is plurisubharmonic if and only if the Hessian matrix $H_u(z)(\omega, \omega)>0$ I'm trying to show that the theorem in my book:

A $C^2$-function $u$ is plurisubharmonic if and only if the matrix
  (the complex Hessian) $$H_u(z)=\left( \dfrac{\partial^2
u}{\partial z_j \partial \bar z_k} \right)$$ is positive semidefinite. It means that $\forall \omega=(\omega_1, \ldots, \omega_n) \in \Bbb{C}^n$ then
$$H_u(z)(\omega,\omega)=\sum_{j,k=1}^{n}\dfrac{\partial ^2 u}{\partial z_j \partial \overline{z_k}}(z)\cdot \omega_j \overline{\omega_k}\ge 0$$

Solution
$\bigstar $ We'll prove that $\forall z \in \Omega, \omega \in \Bbb C^n,\xi \in \Bbb C $ then $$\dfrac{1}{4}\Delta_\xi u(z+\xi\omega)\mid_{\xi=0}=\sum_{j,k=1}^{n}\dfrac{\partial ^2 u}{\partial z_j \partial \overline{z_k}}(z)\cdot \omega_j \overline{\omega_k}$$

*

*Since $\xi=x+iy \in  \Bbb C \implies \left\{\begin{matrix}
 & x=\dfrac{\xi+\overline{\xi}}{2}\\
 & y=\dfrac{\xi-\overline{\xi}}{2i}
\end{matrix}\right.$

*Since $\dfrac{\partial u}{\partial \overline{\xi}}=\dfrac{1}{2}\dfrac{\partial u}{\partial x}-\dfrac{1}{2i}\dfrac{\partial u}{\partial y} \ \text{and} \ \dfrac{\partial u}{\partial {\xi}}=\dfrac{1}{2}\dfrac{\partial u}{\partial x}-\dfrac{i}{2}\dfrac{\partial u}{\partial y}$ we have
$$ \begin{align*}\dfrac{\partial^2 u}{\partial  \xi \partial \overline{\xi}} &=\dfrac{1}{4}\left (\dfrac{\partial^2 u}{\partial x^2}+\dfrac{\partial^2 u}{\partial y^2}  \right )\\ &=\dfrac{1}{4}\Delta _\xi u \tag{I}\end{align*}$$

*Now, I have stuck when I want to show that
$$\dfrac{\partial^2 u (z+\xi\omega)}{\partial  \xi \partial \overline{\xi}}\mid_{\xi=0}=\sum_{j,k=1}^{n}\dfrac{\partial ^2 u}{\partial z_j \partial \overline{z_k}}(z)\cdot \omega_j \overline{\omega_k} \tag{II}$$

$\bigstar $ Since $(I)$ & $(II)$ we're done.
But How can we show that $(II)$?
Any help will be appreciated! Thanks!

A: (II) is a computation with the multivariable chain rule. Applied once, the  rule yields
$$\dfrac{\partial u (z+\xi\omega)}{\partial  \xi }=\sum_{j=1}^{n}\dfrac{\partial  u}{\partial z_j }(z)\cdot \omega_j \tag1$$
Now, if the right side is denoted $g(z)$, we have the analog of (1),
$$\dfrac{\partial g (z+\xi\omega)}{\partial  \overline\xi }=\sum_{k=1}^{n}\dfrac{\partial  g}{\partial \overline z_k }(z)\cdot \overline \omega_k \tag2$$
Plug the formula for $g$ into the right side of (2), and conclude.

A: Show that $(II)$:

*

*We have: $$\forall z \in \Omega \subset \Bbb C^n, \omega \in \Bbb C^n, \xi \in \Bbb C \implies z+\xi \omega =\left (z_1+\xi \omega_1,\ldots, z_n+\xi \omega_n  \right ) \in \Bbb C^n$$

*Applying the multivariable chain rule, we have: $$\dfrac{\partial u (z+\xi\omega)}{\partial  \xi }\mid_{\xi=0}=\sum_{j=1}^{n}\dfrac{\partial  u}{\partial z_j }(z)\cdot \omega_j:=g(z) $$

*Thus, LHS of $(I)$ becomes:$$\begin{align*}\\ \dfrac{\partial g (z+\xi\omega)}{\partial  \overline\xi }\mid_{\xi=0}&=\dfrac{\partial^2 u (z+\xi\omega)}{ \partial \overline{\xi} \partial  \xi}\mid_{\xi=0}\\ &=\dfrac{\partial }{\partial \overline{\xi} }\left ( \sum_{j=1}^{n}\dfrac{\partial  u}{\partial z_j }(z+\xi \omega)\cdot \omega_j \right )\mid_{\xi=0}\\ &=\sum_{k=1}^{n}\dfrac{\partial^2  u}{\partial z_j \partial \overline z_k }(z)\cdot \omega_j \overline{\omega_k} \blacksquare \end{align*}  $$
We're done!