text:
Q: How can I mock a private property in a class I'm trying to test in jest I have a class method I want to test:
setStepResolution(resolution: stepResolution): void {
        switch (resolution) {
            case stepResolution.FULL_SETUP:
                this.stepperMotors.left.ms1Pin.digitalWrite(0)
                this.stepperMotors.left.ms2Pin.digitalWrite(0)
                this.stepperMotors.left.ms3Pin.digitalWrite(1)
                this.stepperMotors.right.ms1Pin.digitalWrite(0)
                this.stepperMotors.right.ms2Pin.digitalWrite(0)
                this.stepperMotors.right.ms3Pin.digitalWrite(1)
                break
            case stepResolution.HALF_STEP:
                this.stepperMotors.left.ms1Pin.digitalWrite(1)
                this.stepperMotors.left.ms2Pin.digitalWrite(0)
                this.stepperMotors.left.ms3Pin.digitalWrite(0)
                this.stepperMotors.right.ms1Pin.digitalWrite(1)
                this.stepperMotors.right.ms2Pin.digitalWrite(0)
                this.stepperMotors.right.ms3Pin.digitalWrite(0)
                break

Each of these digitalWrite calls is made to an instance of a different class that are created when my class is constructed:
export default class BotController {

    private stepperMotors: StepperMotorCollection

    constructor() {
        this.initalizeMotors()
    }

    private initalizeMotors(): void {
        this.stepperMotors = {
            left: {
                directionPin: new Gpio(Number(process.env.LEFT_DIRECTION_PIN), { mode: Gpio.OUTPUT }),
                stepPin: new Gpio(Number(process.env.LEFT_STEP_PIN), { mode: Gpio.OUTPUT }),
                ms1Pin: new Gpio(Number(process.env.LEFT_RESOLUTION_PIN_MS1), { mode: Gpio.OUTPUT }),
                ms2Pin: new Gpio(Number(process.env.LEFT_RESOLUTION_PIN_MS2), { mode: Gpio.OUTPUT }),
                ms3Pin: new Gpio(Number(process.env.LEFT_RESOLUTION_PIN_MS3), { mode: Gpio.OUTPUT }),
                stepsPerMM: Number(process.env.LEFT_STEPS_PER_MM),
                swapCoils: Boolean(process.env.LEFT_SWAP_COILS),
            },
            right: {
                directionPin: new Gpio(Number(process.env.RIGHT_DIRECTION_PIN), { mode: Gpio.OUTPUT }),
                stepPin: new Gpio(Number(process.env.RIGHT_STEP_PIN), { mode: Gpio.OUTPUT }),
                ms1Pin: new Gpio(Number(process.env.RIGHT_RESOLUTION_PIN_MS1), { mode: Gpio.OUTPUT }),
                ms2Pin: new Gpio(Number(process.env.RIGHT_RESOLUTION_PIN_MS2), { mode: Gpio.OUTPUT }),
                ms3Pin: new Gpio(Number(process.env.RIGHT_RESOLUTION_PIN_MS3), { mode: Gpio.OUTPUT }),
                stepsPerMM: Number(process.env.RIGHT_STEPS_PER_MM),
                swapCoils: Boolean(process.env.RIGHT_SWAP_COILS),
            },
        }
    }

I could create a mock for the stepperMotors property in my test with mocks of the Gpio class (I'm already mocking the constructor for some of the other tests):
test("can change step resolution", () => {
        // * The step resolution of the stepper motors can be changed via the code.
        // * The settings can be controlled by an enum that denotes each of the possible
        // * resolutions.

        const mockStepperMotorConfiguration: StepperMotorCollection = {
            left: {
                directionPin: new pigpio.Gpio(1),
                stepPin: new pigpio.Gpio(1),
                ms1Pin: new pigpio.Gpio(1),
                ms2Pin: new pigpio.Gpio(1),
                ms3Pin: new pigpio.Gpio(1),
                stepsPerMM: 1,
                swapCoils: false,
            },
            right: {
                directionPin: new pigpio.Gpio(1),
                stepPin: new pigpio.Gpio(1),
                ms1Pin: new pigpio.Gpio(1),
                ms2Pin: new pigpio.Gpio(1),
                ms3Pin: new pigpio.Gpio(1),
                stepsPerMM: 1,
                swapCoils: false,
            },
        }

        // ^ To change the resolution to a full step
        // * send in the full step enum
        newController.setStepResolution(stepResolution.FULL_SETUP)

But I can't because the stepperMotor property is private.
There are several ways I could solve this (make the property public, make a public method for setting the property), but neither of them seems desirable because the property should never be accessible outside of the class so I would be exposing properties or methods only to support testing.
Is there another way of doing this kind of test? I know in jest I can mock a method on a class in javascript by replacing the prototype function e.g.:
BotController.prototype.someMethod = jest.fn()
const controller = new BotController

And if this was a class I was trying to mock I could pass in the properties as a mock implementation, e.g.:
jest.mock("../BotController", () => ({
    stepperMotors: mockStepperMotorConfiguration
}))

But then everything else in the class would also be mocked and you'd loose the point.
Any idea on how I should approach this?
Update: trying to create a backdoor
I'm trying out Taplar's approach of creating a backdoor.
I tried casting my controller instance as an any:

But the complier is still yelling at me:

Another update
After Taplar pointed out how to call the method on the cast version the errors went away on the back door which is fantastic!
The next wall I smashed into was that now for some reason the test can't see my mock anymore which is weird because the variable is local to the test.

A: Unless # hard privacy is used, private properties can be accessed outside a class at runtime, TypeScript access modifiers are applied only at compilation time.
Accessing private members in tests can be considered a reflection.
Visibility can be bypassed with bracket notation, which is the preferable option:
controllerInstance['stepperMotors'] = ...;

Or with Reflect API:
Reflect.set(controllerInstance, 'stepperMotors', ...);

Or by disabling type checks:
(controllerInstance as any).stepperMotors = ...;

Since private property is set with prototype method, another approach is to mock it. It's applicable if original initialization causes undesirable side effects and needs to be avoided. BotController.prototype.someMethod = jest.fn() should never be used in Jest as it cannot be automatically cleaned up and cross-contaminates tests. Instead it could be:
jest.spyOn(BotController.prototype, 'initalizeMotors').mockImplementation(function (this: BotController) {
  this['stepperMotors'] = ...;
});
...
expect(controllerInstance['initalizeMotors']).toHaveBeenCalled();


text:
Q: Divergence Theorem Problem Let $f,g:R^3\setminus\{0\}\to\mathbb{R}$ be $C^1$, let $\Omega=\{(x,y,z):x^2+y^2+z^2=1, z\geq 0\}$, $\Lambda=\{(x,y,z):0<x^2+y^2+z^2\leq 1, z\geq 0\}$ and $T=\{(x,y,z): x^2+y^2=1, z=0\}$. Show that $|\int\int_{\Omega}\nabla f\times\nabla g\cdot\hat{n}dS|\leq\pi\ \text{sup}_{t\in T}\{|f(t)\nabla g(t)|+|g(t)\nabla f(t)|\}$
My initial thought was since for vectors $A,B,C$ we have $\nabla\cdot(A\times B)=B\cdot(\nabla\times\nabla A)-A\cdot(\nabla\times\nabla B)$, so using the divergence theorem, and substituting $A=\nabla f$ and $B=\nabla g$, we get $\int\int_{\Omega}\nabla f\times\nabla g\cdot\hat{n}dS=\int\int\int_{\Lambda}\nabla\cdot(\nabla f\times\nabla g)dV=\int\int\int_{\Lambda}0dV=0$, so the inequality would be trivial. But I think $\Lambda$ might not have the right properties for divergence theorem to hold (I know closed and bounded is sufficient, but not sure if necessary).
So instead I thought to do the same calculation above except replace $\Lambda$ with $\Lambda_a=\{(x,y,z):a\leq x^2+y^2+z^2\leq 1, z\geq a\}$. Then each $\Lambda_a$ is closed and bounded and the above calculation holds (I think) for each $\Lambda_a$. This means that the only contribution $\int\int_{\Omega}\nabla f\times\nabla g\cdot\hat{n}dS$ can make is the flux through the circle $T$.
Since $|\nabla f\times\nabla g\cdot\hat{n}|=|\nabla f||\nabla g|\text{cos}(\theta_{f,g})\text{cos}\phi\leq |\nabla f||\nabla g|$, where $\phi$ is the angle between $\nabla f\times\nabla g$ and $\hat{n}$, we have $\int_{T}\nabla f\times\nabla g\cdot\hat{n}dl\leq\int_{T}|\nabla f||\nabla g|dl\leq\text{sup}_{t\in T}\{|\nabla f(t)||\nabla g(t)|\}\int_Tdl=2\pi\text{sup}_{t\in T}\{|\nabla f(t)||\nabla g(t)|\}$
This isn't the right bound, so I'm thinking there's something wrong with my approach. Does anyone have any suggestions?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to serialize fields related to a model through another model? My models are as follows:
class Question(models.Model):
    content = models.CharField(
        max_length=1000,
        blank=False,
        default='',
        )

    def __str__(self):
        return self.content

class OptionGroup(models.Model):

    question = models.ForeignKey(
        'Question',
        on_delete=models.CASCADE,
        default='',
        )

    options = models.ManyToManyField('Option')

class Option(models.Model):

    content = models.CharField(
        max_length=1000,
        blank=False,
        default='',
        )

I am trying to create a Question serializer which will serializer Question.content and all the related Option.content without displaying any fields from OptionGroup. How do I do this?

A: Create a SerializerMethod field and define it accordingly:
serializers.py
from rest_framework import serializers

from diagnosisApp.models import Question, Option

class OptionSerializer(serializers.ModelSerializer):

    class Meta:
        model = Option
        fields = ('id', 'content')

class QuestionSerializer(serializers.ModelSerializer):
    options = serializers.SerializerMethodField()

    class Meta:
        model = Question
        fields = ('content', 'options')

    def get_options(self, obj):
        selected_options = Option.objects.filter(
            optiongroup__question=obj).distinct()
        return OptionSerializer(selected_options, many=True).data

A: You can serialize related models by using nested serializers like this:
class OptionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Option
        fields = ('content',)

class QuestionSerializer(serializers.ModelSerializer):
    options = OptionSerializer(many=True, read_only=True)

    class Meta:
        model = Question
        fields = ('content', 'options')

Which will give the following result:
{
    'content': 'some content',  # your Question
    'options': [
        {'content': 'some content'},  # related Option
        {'content': 'some other content'},  # related Option
        ...
    ],
}

You can read more about nested serializers here.

A: models:
class OptionGroup(models.Model):

    question = models.ForeignKey(
        'Question',
        on_delete=models.CASCADE,
        default='',
        related_name='question_options'
        )

    options = models.ManyToManyField('Option')

class Question(models.Model):
    content = models.CharField(
        max_length=1000,
        blank=False,
        default='',
        )
    # options = models.ManyToManyField('Option', through='OptionGroup')
    def get_options(self):
        options = self.question_options.all().values('options')
        option_ids = []
        for option in options:
            option_ids.append(option['options'])
        return Option.objects.filter(id__in=option_ids)
    def __str__(self):
        return self.content

class Option(models.Model):

    content = models.CharField(
        max_length=1000,
        blank=False,
        default='',
        )

    def __str__(self):
        return self.content

serializers
class OptionSerializer(serializers.ModelSerializer):

    class Meta:
        model = Option
        exclude = ('id',)

class QuestionSerializer(serializers.ModelSerializer):
    options = serializers.SerializerMethodField(read_only=True)

    def get_options(self, obj):
        options = obj.get_options()
        return OptionSerializer(options, many=True).data

    class Meta:
        model = Question
        fields = "__all__"


text:
Q: Change zsh theme if too long If I have an ohmyzsh theme that uses %~/ to get the current directory path. Is there a way to tell it that if the line length requires wrapping onto a new line, to use just the current directory without the full path?

A: Not exactly, but Zsh can actually do something better than that! You can use %-X<Y<Z%<< to ensure you always have at least X characters remaining after your prompt, by trimming the left side of Z and replacing the trimmed part with Y. (Note that Y itself is always printed literally and any prompt escape sequences inside it will not be expanded. If you want to style Y differently from Z, you will have to put the prompt escapes before and after %X<Y<.)
For example:
PS1=$'\n%-40<...<%~%<<%# '

What this does:

*

*If expanding %~ would leave 40 or more characters of empty space on the line, then expand it in full.

*Else, print a ... to the left of %~ and trim off characters from the left of %~'s expansion until our prompt leaves exactly 40 characters of empty space on the line.

*Always expand %#  after this (since it occurs after %<<).

The nice thing about this is that it works for the current prompt even when you resize your terminal. Just try it and you'll see it will dynamically add or remove characters as you resize.


text:
Q: When JavaScript returns null & undefined? I have been using JavaScript for couple of years and never cared about the difference between null & undefined earlier, I always use undefined to validate the object existence.
But recently I came through this article. Here they said

JavaScript distinguishes between null, which is an object of type 'object' that indicates a deliberate non-value, and undefined, which is an object of type 'undefined' that indicates an uninitialized value — that is, a value hasn't even been assigned yet. We'll talk about variables later, but in JavaScript it is possible to declare a variable without assigning a value to it. If you do this, the variable's type is undefined.

I am completely confused now, what exactly is non-value here. How this non-value differs from undefined. And what are the circumstances javascript returns null.
I have tried the below sample
var sam;
alert(sam);  // returns undefined

And
try {
    //var sam;
    alert(sam);
} catch(ex) { }   // exception says: sam is undefined

And I am not sure about when js returning nulls. Can someone clarify me.

A: <script type="text/javascript">
// variable with an unasigned value
var a;
if (a == undefined) {
  alert('a is undefined');
}

if (a == null) {
  alert('a is undefined');
}

// this will produce an error
if (b == undefined) {
  alert('b is undefined');
}

// this is the right way to handle not defined variables
if (typeof(c) == 'undefined') {
  alert('c is blabla');
}
</script>

A: For a variable to receive a null value it must be assigned.  null is used to indicate an unknown or don't care value.  undefined on the other hand is designed to indicate that the propery being accessed has never ben assigned a value.  This differs from null.
With null one is deliberately saying "I don't know what value this should have yet" or "I don't care what value this is right now".  OTH in undefined is really saying "Are you sure you should be using this value it hasn't been assigned".

A:
alert(sam);     // returns undefined

Nope, that's an exception.
You get undefined when you access an unset property; you get an error when you use an unset name directly.
Global variables are interesting because they can be accessed either using a simple variable name, or by using properties of the window global object:
alert(window.sam);      // undefined
alert(window['sam']);   // undefined
alert('sam' in window); // false
alert(sam);             // ERROR

If sam is declared but not initialised, accessing window.sam still gets you undefined, but for a different reason: there is an entry in the window object for sam, but it points to the same undefined object as you get when you access a non-existant property.
var sam;
alert(window.sam);      // undefined
alert(window['sam']);   // undefined
alert('sam' in window); // ** true
alert(sam);             // ** undefined

This is of course a confusing bloody mess; undefined is one of the worst mistakes in the design of the JavaScript language.
null on the other hand is fine and works pretty much the same as null/nil/void/None values in other languages. It doesn't come into any of the above.

A: The way I distinguish them is undefined being "I have not defined this value," and null being "I have defined this value, but I do not know or cannot figure out what the value should be."


text:
Q: Connection closed log lines in auth.log on Debian machines My auth.log on my Debian machines was full of the following messages:
CRON[1736]: pam_unix(cron:session): session opened for user root by (uid=0)
sshd[1742]: Connection closed by ::1 port 38518 [preauth]
CRON[1736]: pam_unix(cron:session): session closed for user root
sshd[1748]: Connection closed by ::1 port 38592 [preauth]
CRON[1752]: pam_unix(cron:session): session opened for user root by (uid=0)
sshd[1758]: Connection closed by ::1 port 38672 [preauth]
...

As per the instructions here I added the following line to /etc/pam.d/common-session-noninteractive:
session    [success=1 default=ignore] pam_succeed_if.so service in cron quiet use_uid

However, the following lines keep being added to the auth.log file:
Jun 17 10:39:47 <machine> sshd[2175]: Connection closed by ::1 port 41262 [preauth]
Jun 17 10:40:21 <machine> sshd[2188]: Connection closed by ::1 port 41340 [preauth]
Jun 17 10:40:54 <machine> sshd[2194]: Connection closed by ::1 port 41416 [preauth]
Jun 17 10:41:28 <machine> sshd[2205]: Connection closed by ::1 port 41494 [preauth]
Jun 17 10:42:02 <machine> sshd[2228]: Connection closed by ::1 port 41576 [preauth]
Jun 17 10:42:35 <machine> sshd[2235]: Connection closed by ::1 port 41668 [preauth]
Jun 17 10:43:09 <machine> sshd[2246]: Connection closed by ::1 port 41764 [preauth]
Jun 17 10:43:42 <machine> sshd[2252]: Connection closed by ::1 port 41842 [preauth]
Jun 17 10:44:16 <machine> sshd[2262]: Connection closed by ::1 port 41922 [preauth]
Jun 17 10:44:50 <machine> sshd[2269]: Connection closed by ::1 port 41998 [preauth]
Jun 17 10:45:23 <machine> sshd[2285]: Connection closed by ::1 port 42084 [preauth]
Jun 17 10:45:57 <machine> sshd[2292]: Connection closed by ::1 port 42164 [preauth]
...

And I'm not sure how to get rid of these. First of all it shows IP(v6) ::1 (so localhost). But just to be sure: the host is not reachable from the outside world (let alone via IPv6, since IPv6 is not enabled on my connection) and is behind an OpenBSD gateway/firewall. ::1 is most likely something ran on my local machine. So I was pretty sure it came from a cronjob that is run every minute. And that cronjob looks a bit like this:
php foo.php
sleep 30
php foo.php

Which is just a (shitty) way to run a PHP script every 30 seconds. The script finishes in seconds.
However, what is weird is if you look at the log times. You'd expect an entry at the whole minute (+/- a second or two) and then, maybe, another one every half minute (+/- a few seconds depending on how long the first script took + 30 seconds). But that's not the case. The time between each log line is 34, 33, 34, 34, 33, 34, 33, 34, 34, 33, 34, ... seconds respectively. That means the time is 'drifting'.
Even weirder: if I comment out the crobtab line with the job running every minute then the "Connection closed by..." lines KEEP coming. Even though that particular job/script was disabled. So that tells me it's probably not the cronjob causing these lines. There's no other cronjobs that would explain this either.
I then ran a tcpdump:
tcpdump -i lo port 22

And, sure enough, if I wait a little I see traffic come in:
11:18:29.548247 IP6 localhost.46846 > localhost.ssh: Flags [S], seq 1675216317, win 43690, options [mss 65476,sackOK,TS val 1107033 ecr 0,nop,wscale 7], length 0
11:18:29.548270 IP6 localhost.ssh > localhost.46846: Flags [S.], seq 3867254410, ack 1675216318, win 43690, options [mss 65476,sackOK,TS val 1107033 ecr 1107033,nop,wscale 7], length 0
11:18:29.548279 IP6 localhost.46846 > localhost.ssh: Flags [.], ack 1, win 342, options [nop,nop,TS val 1107033 ecr 1107033], length 0
11:18:29.551956 IP6 localhost.ssh > localhost.46846: Flags [P.], seq 1:40, ack 1, win 342, options [nop,nop,TS val 1107034 ecr 1107033], length 39
11:18:29.551967 IP6 localhost.46846 > localhost.ssh: Flags [.], ack 40, win 342, options [nop,nop,TS val 1107034 ecr 1107034], length 0
11:18:29.551982 IP6 localhost.46846 > localhost.ssh: Flags [P.], seq 1:40, ack 40, win 342, options [nop,nop,TS val 1107034 ecr 1107034], length 39
11:18:29.552005 IP6 localhost.ssh > localhost.46846: Flags [.], ack 40, win 342, options [nop,nop,TS val 1107034 ecr 1107034], length 0
11:18:29.552448 IP6 localhost.ssh > localhost.46846: Flags [P.], seq 40:792, ack 40, win 342, options [nop,nop,TS val 1107034 ecr 1107034], length 752
11:18:29.552475 IP6 localhost.46846 > localhost.ssh: Flags [F.], seq 40, ack 792, win 354, options [nop,nop,TS val 1107034 ecr 1107034], length 0
11:18:29.552778 IP6 localhost.ssh > localhost.46846: Flags [F.], seq 792, ack 41, win 342, options [nop,nop,TS val 1107034 ecr 1107034], length 0
11:18:29.552784 IP6 localhost.46846 > localhost.ssh: Flags [.], ack 793, win 354, options [nop,nop,TS val 1107034 ecr 1107034], length 0
11:19:03.202403 IP6 localhost.46962 > localhost.ssh: Flags [S], seq 4240077294, win 43690, options [mss 65476,sackOK,TS val 1115447 ecr 0,nop,wscale 7], length 0
11:19:03.202427 IP6 localhost.ssh > localhost.46962: Flags [S.], seq 3703193700, ack 4240077295, win 43690, options [mss 65476,sackOK,TS val 1115447 ecr 1115447,nop,wscale 7], length 0
11:19:03.202442 IP6 localhost.46962 > localhost.ssh: Flags [.], ack 1, win 342, options [nop,nop,TS val 1115447 ecr 1115447], length 0
11:19:03.206034 IP6 localhost.ssh > localhost.46962: Flags [P.], seq 1:40, ack 1, win 342, options [nop,nop,TS val 1115448 ecr 1115447], length 39
11:19:03.206044 IP6 localhost.46962 > localhost.ssh: Flags [.], ack 40, win 342, options [nop,nop,TS val 1115448 ecr 1115448], length 0
11:19:03.206077 IP6 localhost.46962 > localhost.ssh: Flags [P.], seq 1:40, ack 40, win 342, options [nop,nop,TS val 1115448 ecr 1115448], length 39
11:19:03.206093 IP6 localhost.ssh > localhost.46962: Flags [.], ack 40, win 342, options [nop,nop,TS val 1115448 ecr 1115448], length 0
11:19:03.206573 IP6 localhost.ssh > localhost.46962: Flags [P.], seq 40:792, ack 40, win 342, options [nop,nop,TS val 1115448 ecr 1115448], length 752
11:19:03.206601 IP6 localhost.46962 > localhost.ssh: Flags [F.], seq 40, ack 792, win 354, options [nop,nop,TS val 1115448 ecr 1115448], length 0
11:19:03.206981 IP6 localhost.ssh > localhost.46962: Flags [F.], seq 792, ack 41, win 342, options [nop,nop,TS val 1115448 ecr 1115448], length 0
11:19:03.206986 IP6 localhost.46962 > localhost.ssh: Flags [.], ack 793, win 354, options [nop,nop,TS val 1115448 ecr 1115448], length 0

And about 33/34 seconds later more traffic coming in. But, again, no clue as to where this is coming from...
So I have 2 questions:

*

*How do I find out which process / whatever is causing these loglines

*How do I get rid of these loglines (which may be depending on 1 ofcourse)

A: Never mind, I figured it out. It was monit monitoring the SSH deamon. I'm a dumbass. I stopped monit (service monit stop), tailed the auth.log and, whaddayaknow, no more entries. So mystery solved and monit was restarted. Now I know the cause, I don't mind these loglines as much.


text:
Q: How to delete the autofill data stored by Chrome? How to delete the autofill data stored by Chrome which keeps popping up every time I bring my cursor to a blank field?

A: This can be done easily in Google Chrome using Shift+Delete. Now if you wish to delete the entire autofill history for a certain period, clear the browser history for the period
For selective deletion,

*

*Click on the field with the undesired autofill.

*In the dropdown menu that appears, bring the selection to the autofill entry you wish to delete

*Press Shift+Delete
Also remember that it's always convenient to browse in cognito when you don't want your data to get automatically stored.


text:
Q: Install SSM Agent and Role suring Launch on SUSE Linux EC2 Instance in AWS My customer has no public subnet, has all private subnets without any NAT Gateway and Elastic IP. I have to launch new EC2 instance with SLES 12 and SLES 15 that can be connected through SSM. Will you please guide me how can I install SSM agent and required role during launch of EC2 instance?
I have created a SSM role with AmazonEC2RoleforSSM policy.
I tried the below mentioned commands in bootstarp but it is not working
mkdir /tmp/ssm
cd /tmp/ssm
wget https://s3.ca-central-1.amazonaws.com/amazon-ssm-ca-central-1/latest/linux_amd64/amazon-ssm-agent.rpm
sudo rpm --install amazon-ssm-agent.rpm
sudo systemctl enable amazon-ssm-agent
sudo systemctl start amazon-ssm-agent
Please help.

A: With this setup, the ec2 instances may not be able to get connected to the Internet. You can try to bake an image with necessary packages and SSM agent installed then provision the instances with it.


text:
Q: Can we claim that $A \cap B$ or $A \cup B$ is not in $\mathcal{B}(\mathbb{R}^n))$? This question can be posed for more general sigma algebras, but let's stick to $(\mathbb{R}^n, \mathcal{B}(\mathbb{R}^n))$ for now. Suppose $A \in \mathcal{B}(\mathbb{R}^n))$, and $B_n \notin \mathcal{B}(\mathbb{R}^n))$.

*

*Can we claim that $A \cap B$ or $A \cup B$ is not in $\mathcal{B}(\mathbb{R}^n))$?

*Then what about $\bigcup_{n\in \mathbb{N}} B_n$ or $\bigcap_{n\in \mathbb{N}} B_n$; can we claim that these sets are not measurable?
(I'm asking because I don't have a proof. This is a question that has crossed my mind several times, but I've never been able to satisfactorily prove/disprove.)

A: The answer to 1 is negative, $A\cap B$ can be measurable, for example if $A$ and $B$ are disjoint (or meet in a single point if you don't want them to be disjoint), while $A\cup B$ can be measurable as well, for example if $B\subseteq A$.
For 2 the answer is also negative, countable unions of nonmeasurable sets can be measurable, in fact even finite unions can, just pick a nonmeasurable set and its complement for example.
Edit: after reading Daniel's answer I realized I probably misread the "or" in your question. My example for question 2 however does show that both $\bigcup B_n$ and $\bigcap B_n$ can be measurable when none of the $B_n$ are, so I'll leave my answer here

A: For 1: Suppose, to the contrary, that both $A\cup B$ and $A\cap B$ were measurable.  Then $A \mathop{\triangle} B = (A\cup B) \setminus (A\cap B)$ is also measurable, where $A \mathop{\triangle} B$ denotes the symmetric difference.  Therefore, $B = A \mathop{\triangle} (A \mathop{\triangle} B)$ would also be measurable, giving a contradiction.  Thus, we conclude that if $A$ is measurable but $B$ is not measurable, then at least one of $A\cup B$ or $A\cap B$ must be non-measurable.


text:
Q: How to get frame line at the last element of array I have a question regarding my code. I want to print a playfield which looks like this:
|     |
|     |
|     |
|     |
-12345-

This is my code:
void PrintBoard(char* argv[])
{
  int width_of_gamefield = atoi(argv[2]);
  int height_of_gamefield = atoi(argv[3]);

  for(int j = 0; j <= height_of_gamefield -1; j++)
  {
    printf("%s\n", "|");
  }
  printf("%s", "-");
  for(int i = 1; i <= width_of_gamefield; i++)
  {
    printf("%d", i);
  }
  printf("%s", "-");
}

And what i get is this:
|
|
|
|
-12345-

How do i print the right side?

A: Try this instead:
  for(int j = 0; j < height_of_gamefield; j++)
  {
    printf("%s%*s\n","|", width_of_gamefield,"|");
  }

The %*s allows you to specify a variable number for the string padding.


text:
Q: HTML PHP email code not working Please can anyone see any errors in this PHP code, I have tried everything I can think of with no luck, I am trying to get a form to send the data to the PHP and then send an email but every time I try on the server all I get is the 'Message failed.'
 <?php
    $field_name = $_POST['cf_name'];
    $field_email = $_POST['cf_email'];
    $field_message = $_POST['cf_message'];

    $mail_to = 'MyEmail@hotmail.co.uk';
    $subject = 'Message from a site visitor '.$field_name;

    $body_message = 'From: '.$field_name."\n";
    $body_message .= 'E-mail: '.$field_email."\n";
    $body_message .= 'Message: '.$field_message;

    $headers = 'From: '.$field_email."\r\n";
    $headers .= 'Reply-To: '.$field_email."\r\n";

    $mail_status = mail($mail_to, $subject, $body_message, $headers);

    if ($mail_status) { ?>
        <script language="javascript" type="text/javascript">
            alert('Thank you for the message. We will contact you shortly.');
            window.location = 'default.html';
        </script>
    <?php
    }
    else { ?>
        <script language="javascript" type="text/javascript">
            alert('Message failed.');
            window.location = 'default.html';
        </script>
    <?php
    }
    ?>


text:
Q: Redirecting my website to another website in Route53 I want to know how can I redirect my website to another website (through domain name or IP address) using AWS Route53.
What I have done so far is,
1) I have bought a domain name.
2) I have generated AWS Route53 Name servers (NS) for the website and registered these NS on the domain name provider.
Now, suppose my website name is thisnewsite.com and I want that when users put thisnewsite.com or www.thisnewsite.com on browser, they should be redirected to
1)some other website, for example, www.flaticon.com, or
2)some IP address like xxx.xxx.xxx.xxx, or
3)some IP address with port like xxx.xxx.xxx.xxx:xxx
What is the Route53 method to do this?

A: 1) For URL forwarding, see this answer: https://stackoverflow.com/a/14289082/902751
2) For IP redirect, create a record set of type A - IPv4 address that maps your host name to your IP address. This is an example (for EC2, but it will work for any IP): https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-to-ec2-instance.html
3) For IP redirect with port: Route 53 cannot do that. In fact, DNS in general does not care about port. It only maps domain names to IP addresses. A potential solution would be set up a proxy that would redirect your request from port A to port B.


text:
Q: One vector data layer with different styles in QGIS I have one layer of vector data that I would like to show in two different styles. Is there a way of accomplishing this in QGIS?
I've solved it now by duplicating the the vector layer and add separate styles for the two layers. That works, but there is one problem with this; When I edit an attribute in one of those two layers, the edited data does not appear in the other layer and the categorized symbols do not longer represent the updated data. I have to hit "Refresh" (F5) to make the edited data update in the other layer. This takes time, since there are many other layers in the project and is not a good solution.
Is there a better way of doing this? I'm pretty sure that this can be done in MapInfo and ArcGis where it's possible to have multiple themes (styles in QGIS) for one layer.
The layers are in WFS format.

A: I'm told that in the upcoming QGIS 2.6 when joining multiple layers via the JOINS option (Layer Properties > Joins), editing the attributes of one layer will immediately update the attributes of the joining layers so basically in real-time.
If this is the case then you could create a duplicate of the same layer, save it as another shapefile, edit its attributes and remove all but one column (ideally like an "ID" column or similar). Then do a JOINS to connect both layers.
Although this is a possible solution for QGIS 2.6, I'm not sure if there's a better method than what you have already done.
QGIS 2.6 is currently scheduled for 2014/10/31.


text:
Q: How to store downloaded images in to android SD card Hi I am developing app which downloads the images from the web site
and then i am displaying them as slide show.  Now I want save the
downloaded images into my SD card please help me.
My current attempt is:
File imageFileFolder = new File(Environment
               .getExternalStorageDirectory(), "test");
imageFileFolder.mkdir();
File imageFileName = new File(imageFileFolder, date
               + pBean.getAuthorName());

InputStream fis = pBean.getInputStream();

byte[] data = new byte[fis.available()];
fis.read(data);
FileOutputStream fos = new FileOutputStream(imageFileName);
fos.write(data);
fos.close();
fis.close();

A: There are lot of examples available for this
Check this post
Lazy load of images in ListView
and link
http://open-pim.com/tmp/LazyList.zip

A: In your AndroidManifest.xml you'll need to add the permission to write
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

Then just get get the path to your filename and make sure your directories exist before trying to write the file to the sdcard.
String imageFileName = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/somedirectory/imagename.jpg"


text:
Q: BASH scripting : Command result and pipeline
Possible Duplicate:
unix shell, getting exit code with piped child

is it possible to have the result of a command (what's usually in $? variable) which is at the beginning of a pipeline ?
eg :
rm -rf filename_to_delete | tee -a log_filename

$? would contain the exit value of the tee statement, how can I have the exit value of the rm statement ?

A: How do I get the exit code of cmd1 in cmd1|cmd2


text:
Q: Remove sub-menu span in wp_nav_menu I have a piece of HTML menu which I want to display in Wordpress with wp_nav_menu.
The HTML

Home

Home Alternate 2

Home Alternate 3

Home Alternate 4

Home Alternate 5

Home Alternate 6

I am adding the following in my Wordpress header.php file to display the nav menu
$defaults = array(
               'theme_location'  => 'primary',
               'menu'            => 'Primary Menu',
               'container'       => '',
               'container_class' => '',
               'container_id'    => '',
               'menu_class'      => 'menu',
               'menu_id'         => '',
               'echo'            => true,
               'fallback_cb'     => 'wp_page_menu',
               'before'          => '',
               'after'           => '',
               'link_before'     => '',
               'link_after'      => '',
               'items_wrap'      => '
%3$s
',
               'depth'           => 0,
               'walker'          => ''
             );
wp_nav_menu($defaults);

However the output is adding the  tags also in the second level of the menu items as

Home

Home Alternate 2

Home Alternate 3

Home Alternate 4

Home Alternate 5

Home Alternate 6

Is there a way to add the span only for the top level menu item or remove the spans from the second level items?

A: add_filter( 'wp_nav_menu_objects', function( $items ) {
      foreach ( $items as $item ) {
        if (!$item->menu_item_parent) {
           $item->title = '' . $item->title . '';
        }
    }
    return $items;
});

A: Ok, While walker seems to be one good way of getting this done, it seems to be pretty elaborate with many lines of codes. I just found out that the easiest way to remove the span for the sub-menu items is with jQuery. Wordpress automatically adds the sub-menu class to the child ul and hence what worked for me was
$('ul.sub-menu li a span').contents().unwrap();

Hope this helps.

A: Using CSS you can hide the sub-menu of wp_nav_menu
.sub-menu { display:none; }


text:
Q: Why is Break needed when using Switch? I've read quite a few answers on SO but can't seem to find a definitive answer as to why if break is omitted in this instance the case "C" will always be evaluated as true and the new array filled will only "G"'s.  I clearly understand that break would be best used here as I am only looking to evaluate a specific match but not so as to why the last case is always true if break is indeed omitted.
 var dna = "ATTGC";
 var outArr = [];
 dna.split("").forEach(function(e,i){
    switch(e) {
        case "G": outArr[i] = "C"; break;
        case "T": outArr[i] = "A"; break;
        case "A": outArr[i] = "T"; break;
        case "C": outArr[i] = "G"; break;
    }
    console.log(outArr);
  })

A: From MDN

If a match is found, the program executes the associated statements. If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.
The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

So the basic history about Switch is it originated from C and is an abstraction of branch table and a branch table also has an implicit fall-through and requires an additional jump instruction to avoid it.
Also all other languages inherited switch as default C switch semantics mostly choosing to keep the C semantics per default.
So in your switch if break is omitted from all cases, if the match is found program continues execution for next statement. It doesn't exit from switch after the match is found instead it evaluates all other case below the matched case, as parser thinks cases are combined, since there is no break in between them.
I have modified your code a bit for clear explanation of this behavior.In case A break is omitted.
var dna = "ATTGC";
var outArr = [];
dna.split("").forEach(function(e,i){
switch(e) {
    case "G": outArr[i] = "C"; break;
    case "T": outArr[i] = "A"; break;
    case "A": outArr[i] = "T";
    case "C": outArr[i] = "G"; break;
}
console.log(outArr);
})

So your Output will be like
["G"]
["G", "A"]
["G", "A", "A"]
["G", "A", "A", "C"]
["G", "A", "A", "C", "G"]

In first iteration match will be for case A.
outArr={'T'}

Again Since there is no break statement, it will consider Case C as same block and continues execution there. Now
outArr={'G'}

Similalrly in second iteration it matches for case T but there is a break statement so controls jumps out of the switch and outarr will now be
outArr={'G','A'}

Similarly for other iterations you will get the whole output as posted above.

Updated Bin here

A: switch and if/else are somewhat interchangeable, EXCEPT for exactly what break allows for in a switch. In and if/elseif/elseif/..../else chain, only ONE of the blocks will ever execute, e.g.
x = 7;
if (x == 5) {
    ... no match, not executed at all
} else if (x == 7) {
   .... match made, this is executed
} else if (x == 7) {
   ... this will not execute, because the other block already did
} else {
   ... this also never executes, because a match was made earlier
}

In comparison, with a switch, once a match is made, no further comparison tests are done, and ALL code following will be executed, until the switch block closes (}), or a break is encountered:
x = 7;
switch(x) {
    case 5:   ... nothing matched, not executed; break;
    case 7: do_something();
    case 8: other_stuff();
    case 9: foo(); break;
    case 7: ... will not execute, because matching stopped above.
    default: stuff();
}

Note the lack of a break on the case 7 line. That means execution continues, and ignores all further case lines. that means do_something() executes, then other_stuff() executes, and foo() executes. Finally a break is encountered, which terminates this now long-running case, and the execution then proceeds on with whatever comes AFTER the switch.

A: When a case matches, if you don't break, it will continue onto the next case regardless of whether it matches the condition. So they will all hit the last case and the output will be overridden with "G"


text:
Q: WCF DuplexChannel - Connection Without Callback I have a WCF Interface which has defined a Callback. This is working very well.
Now I have another Client which don't need the callback. I wanted to know if there is a way to connect to the service also without specifying a callback object?
I tried without the DuplexChannel factory, or DuplexChannelFactory with InstanceContext (null), both it didn't work!
Is there a way to do it?

A: The best way would be to create another interface without the CallbackContract and expose that on a separate Endpoint. That would give you a clean separation between the two code paths and the client could choose which one to use.

A: I now tryed with this the class from here: http://www.codeproject.com/Articles/22832/Automatic-Interface-Implementer-An-Example-of-Runt
worked very well!


text:
Q: How to run python codes (not in views) periodically in Django Framework? I am using Django Framework to write a middleware. Basically, every week, it calls an external API to receive a xml file, does some data processing and sends the results to RabbitMQ.
I am new to Django Framework. I wrote some python files to achieve the logic, but these files did not execute when running the server. I am wondering how to run these codes periodically which are not inside views.
Thank you.


text:
Q: What can be said of the element x if $x \in \cup \{ A-B|A \in F\}$? Having a hard time analyzing the statement. What can be said of the element x if $x \in \cup \{ A-B|A \in F\}$? Disregarding intersection first, I have encountered somewhat similar forms but they were not applied to sets. Example: $y \in \{n^2|n \in N \} $ is transformed as $\exists y \in N(y=n^2)$ (from book). How to deal this types but with sets?
For now, this is my attempt:
$$x \in \{ y| \exists M(M \in \{ A-B|A \in F\} \land y \in M )\}$$
$$\exists M(M \in \{ A-B|A \in F\} \land x \in M )$$
$$\exists M(\exists M(M \in F \land ( M-B)) \land x \in M )$$
I am not sure about the transition to the 2nd to the 3rd line.
Subquestions related to the problem.

*

*Are $y \in\{x \in S|P(x)\}$ and $y \in\{P(x)|x \in S\}$ different? I think the former is $\forall y \in SP(y)$ and the latter is $\exists y \in SP(y)$?

*$\exists M$ appeared twice is there away to make the analysis simpler?
Soft question. What tags should I use for these kinds of question?

A: Well in a slightly simpler case you have
$$ x\in \bigcup_{A\in F}A \quad \Leftrightarrow \quad \exists A\in F(\exists y\in A(x=y))$$
And so we follow this pattern to get
\begin{align*}&x\in\bigcup_{A\in F}(A-B)\\\Leftrightarrow& \exists A\in F(\exists y\in (A-B)(x=y))\\\Leftrightarrow& \exists A\in F(\exists y\in A(\forall b\in B(y\ne b\land y=x)))\end{align*}


text:
Q: displaying listbox in grid This might be a stupid question, but i'm stuck doing it :(. I have a grid and have 3 columns. I have a textbox and a listbox in each of these 3 columns as shown:
<Grid.ColumnDefinitions>
                <ColumnDefinition Width="130"></ColumnDefinition>
                <ColumnDefinition Width="380"></ColumnDefinition>
                <ColumnDefinition Width="146"></ColumnDefinition>
             </Grid.ColumnDefinitions>

            <Grid.RowDefinitions>
                <RowDefinition Height="30"></RowDefinition>
            </Grid.RowDefinitions>
            <StackPanel Grid.Column="0" Grid.Row="0">
                <TextBox Text="File Name" Height="30"></TextBox>
            </StackPanel>
            <StackPanel Grid.Column="1" Grid.Row="0">
                <TextBox Text="File Path" Height="30"></TextBox>
            </StackPanel>
            <StackPanel Grid.Column="2" Grid.Row="0">
                <TextBox Text="File Size" Height="30"></TextBox>
            </StackPanel>

            <StackPanel Grid.Column="0">
                <ListBox Name="listbox_name" Margin="1,30" Height="276" />
             </StackPanel>
            <StackPanel Grid.Column="1">
                <ListBox Name="listbox_path" Margin="1,30" Height="276" />
            </StackPanel>
            <StackPanel Grid.Column="2">
                <ListBox Name="listbox_size" Margin="1,30" Height="276" />
            </StackPanel>

and the code behind it:
public Window1()
        {
        InitializeComponent();

        list.Add("D:\\a\\hy");
        list.Add("D:\\a\\hy1");
        list.Sort();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        listbox_name.ItemsSource = list;
        grid1.Visibility = Visibility.Hidden;
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        grid1.Visibility = Visibility.Visible;
    }

But on the click of the button, im not able to see the listboxes, with the list displayed. Please guide me as to where im going wrong. Thanks!

A: The reason is that your stackPanel is in Grid.Col="0" and it is very small. But ListBox is inside of your stackPanel. It has a margin and it goes down. Is you can't see your listBox.

If you will do something like this:
<StackPanel Margin="0,0,0,-279">
            <ListBox Name="listbox_name" Margin="1,30" Height="276" />
        </StackPanel>

you will see your listBox and it will work.

NOTE: this code is only example. You need to make a better layout for your window.

Here is how i made a window loyout:
<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="678" Loaded="Window_Loaded">
    <Grid Name="grid1">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="130"></ColumnDefinition>
            <ColumnDefinition Width="380"></ColumnDefinition>
            <ColumnDefinition Width="146"></ColumnDefinition>
        </Grid.ColumnDefinitions>

        <Grid.RowDefinitions>
            <RowDefinition Height="30"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>

        <TextBlock Text="File Name"  Grid.Row="0" Grid.Column="0" Margin="5" />
        <TextBlock Text="File Path"  Grid.Row="0" Grid.Column="1" Margin="5" />
        <TextBlock Text="File Size" Grid.Row="0" Grid.Column="2" Margin="5" />

        <ListBox Name="listbox_name" Grid.Row="1" Grid.Column="0" BorderBrush="Black" />
        <ListBox Name="listbox_path" Grid.Row="1" Grid.Column="1" BorderBrush="Black" />
        <ListBox Name="listbox_size" Grid.Row="1" Grid.Column="2" BorderBrush="Black" />
    </Grid>
</Window>

A:     <ListView Name="list"
              Grid.Row="1"
              ItemsSource={Binding Path=Files}
              >
    <ListView.View>
     <GridView>
        <GridViewColumn Header="Name">
            <GridViewColumn.CellTemplate>
                <DataTemplate>
                    <Button>
                     <TextBlock Text="{BindingPath=Name}"/>
                    </Button>
                </DataTemplate>
            </GridViewColumn.CellTemplate>
        </GridViewColumn>
        <GridViewColumn Header="Size">
            <GridViewColumn.CellTemplate>
                <DataTemplate>
                    <Button>
                     <TextBlock Text="{BindingPath=Size}"/>
                    </Button>
                </DataTemplate>
            </GridViewColumn.CellTemplate>
        </GridViewColumn>
        <GridViewColumn Header="Path">
            <GridViewColumn.CellTemplate>
                <DataTemplate>
                    <Button>
                     <TextBlock Text="{BindingPath=Path}"/>
                    </Button>
                </DataTemplate>
            </GridViewColumn.CellTemplate>
        </GridViewColumn>
    </GridView>
     </ListView.View>
    </ListView>

My your ViewModel will be
public class FileListViewModel : INotifyPropertyChanged
{
    /// <summary>
    ///
    /// </summary>
    public ObservableCollection<Fileinfo> Files{ get; set; }

    private Fileinfo selectedFile;

    public Fileinfo SelectedFile
    {
        get { return selectedFile; }
        set
        {
            selectedFile= value;
            InvokePropertyChanged(new PropertyChangedEventArgs("SelectedFile"));
        }
    }

    public PersonListViewModel()
    {
                //Loading List
                   Files= new ObservableCollection<Fileinfo>()
              {    //This is temp list you modify accordinh to you logic
                                   new FileInfo{Name = "File32"},
                                   new FileInfo{Name = "File33"},
                                   new FileInfo{Name = "File373"},
                                   new FileInfo{Name = "File393"},
                                   new FileInfo{Name = "File345"},
                                   new FileInfo{Name = "File375"},
                                   new FileInfo{Name = "File395"},
                                   new FileInfo{Name = "File387"},
                                   new FileInfo{Name = "File387"}
                               };
    }

    #region Implementation of INotifyPropertyChanged

    /// <summary>
    ///
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;

    /// <summary>
    ///
    /// </summary>
    /// <param name="e"></param>
    public void InvokePropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, e);
    }

    #endregion
}

Your Model should be like
public class FileinFo: INotifyPropertyChanged
{
    private string size;
    public event PropertyChangedEventHandler PropertyChanged;
    private string name;
    private bool isSelected;

    public string Size
    {
        get { return size; }
        set
        {
            size= value;
            InvokePropertyChanged(new PropertyChangedEventArgs("size"));
        }
    }

    public string Name
    {
        get { return name; }
        set
        {
            name = value;
            InvokePropertyChanged(new PropertyChangedEventArgs("Name"));
        }
    }

    public bool IsSelected
    {
        get { return isSelected; }
        set
        {
            isSelected = value;
            InvokePropertyChanged(new PropertyChangedEventArgs("IsSelected"));
        }
    }

    public void InvokePropertyChanged(PropertyChangedEventArgs e)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, e);
    }
}

You need to set the datacontext of yor View to ViewModel
so lets say your view is named as FileListView.xaml
Then in code behind in the Constructor you can write
this.DataContext= new FileListViewModel();


text:
Q: Destructive interference of electromagnetic waves
So EM waves can have constructive interference and destructive interference right?
If two strips of EM wave intersect at a point in a destructive manner, would their propagation terminate?
If yes, then how would the momentum and force act on this system?

A:
So EM waves can have constructive interference and destructive interference right?

Yes.

If two strips of EM wave intersect at a point in a destructive manner, would their propagation terminate?

No. Just like with any other wave, they'd interfere destructively at that point, but the interference might be different at other points. One can even get standing electromagnetic waves inside a metal box, such as a microwave oven, for example.
As a fun fact, a do-at-home experiment that one can sometimes find is to remove the rotating plate from the microwave and put some chocolate in it. Since it has standing waves, some pieces of the chocolate will melt really fast, while others will not melt at all (showing the waves are interfering destructively at those points). By measuring the distances of the melted parts, one can find the wavelength. By using the microwave's frequency (often found behind the oven), one can get an estimate for the speed of light. While this (clearly) doesn't have much precision, you can get the order or magnitude correctly by playing with chocolate.

A: There is an essential difference between matter waves and EM waves.
If the excited particles of two waves with opposite amplitudes meet, their kinetic energy is dispersed sideways. Ideally, the wave disappears and the temperature of the medium increases.
For EM waves, no medium is needed. The photons of the EM wave do not interact with each other, they (almost always) pass each other unhindered.
However, we notice interference when two EM waves of opposite amplitudes hit an antenna rod. Then the surface electrons on the rod are moved in opposite directions and the electronics only get noise.

A: What you have to remember is that using the word interference has often caused a conceptual problem about the effect of the meeting of two waves in a region of space.
One wave does not affect the other wave in that each individual wave is oblivious to what the other wave is doing.
What is "observed" is the redirection of energy transfer when two waves travel through the same region of space.
So in some locations no energy is propagated whereas in other regions there is a variable amount of energy propagated but overall there is no net loss of energy propagated.
Your diagram is very limited in that you only are showing what happens at one point is space and neglecting what is happening all around.  I cannot find a ripple tank demonstration video of two source interference in which one views the wave pattern edge on (parallel to the surface of the water) rather that from above or below the ripple tank.  If one does view edge on then the transfer of energy in some regions and none in others can clearly be seen.


text:
Q: Flash Change button color with ActionScript2 I have Flash file with buttons in it, and the color of those buttons changes dynamically when flash loads, the color code is taken from XML file and it changes the color of button with
color.setRGB(color_code_from_xml);

And all here works ok. The problem is with hover color on those buttons, it should be always white but I just cant make it happen, after setRGB() loaded color all states of button (over, down, hit) is in that same color.
How to make the buttons keep the hover color white?
Hope this is understandable, I`m totally new to Flash. Thank you very much.

A: var color_code_from_xml:Number = 0xFF0000; // here you will pass your value from XML

var my_color:Color = new Color(my_button);
my_color.setRGB(color_code_from_xml); // my_button turns to color (red) from XML

my_button.onRollOver = function() { // on mouse roll over
    my_color.setRGB(0xFFFFFF); // my_button turns white
}

my_button.onRollOut = function() { // on mouse roll out
    my_color.setRGB(color_code_from_xml);  // my_button restores to color (red) from XML
}

my_button.onPress = function() { // on mouse press
    my_color.setRGB(0x0066FF); // my_button turns blue
}


text:
Q: First Android app not running I am following the steps as in android training google and my activity_main.xml is like
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <EditText android:id="@+id/edit_message"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="@string/edit_message" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_send" />
</LinearLayout>

I have defined the hint strings
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">My First App</string>
    <string name="edit_message">Enter a message</string>
    <string name="button_send">Send</string>
    <string name="title_activity_main">mainActivity</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>

</resources>

But when I click on run button, it shows no activity !

A: in the MainActivity.java have you inserted the code?
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

A: Have you put this code in AndroidManifest file..
 <application
    android:allowBackup="true"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="YourActivityname"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:theme="@android:style/Theme.NoTitleBar" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
 </application>

A: You cannot run an Android application from a .xml file, you must run from a .java file. Choose Run As > Android Application. Also ensure you have an emulator set up and ready or a real device to run on connected and ready.


text:
Q: Multiple symfony3 localized sites in different geographic TLD domains, sharing the same core For the impatients
What should be the routing.yml strategy in a project that will deploy several locales in several domains, some of the locales being "similar", and for which the pages, logic and layouts are absolutely identical?
Context
I have an agency travel. Let's name the public web "catalog". I'm currently having the catalog in Spanish (es_ES) in my .es domain with a Symfony 3 project.
I'll translate it into catalan (ca_ES) into my .cat domain. Next translations are going to be in English UK (en_GB) and Spanish Mexico (es_MX). In the next future, more "spanishes" and more "englishes" will be added, among others.
I currently have 5 main routes in my symfony (there are more, but for the question here, it is enough):
/                       # proposal of value, main message
/viajes                 # index of the catalog
/quienes-somos          # Who we are
/{destination}          # for example "/tailandia")
/{destination}/{trip}   # for example "/tailandia/circuito-norte-sur")

Note that /viajes and quienes-somos are placed before /{destination} for the matcher to catch them properly.
I plan to add about 20 languages or language-variations in the next year.
Deploy strategy
I'm currently having a deployer. The project consists of about 10 .git repos, one for the admin panel, one for the catalog, one for the DDD model, one for the statics, etc.
Domain strategy

*

*When a regional TLD domain is available, my plan is to get them:

*

*http://example.es/

*http://example.cat/

*http://example.mx/

*http://example.co.uk/ etc.

*When not available, I plan to make subdomains or a directory inside a special global domain:

*

*http://it.globalexample.com/

*http://jp.globalexample.com/

*or alternatively:

*

*http://globalexample.com/it/

*http://globalexample.com/jp/
Static routes problems
I forecast spaghetti problems with the routing if I only use a single .git and a single routing.yml.
I don't see having just:
/qui-som        # For Catalan
/chi-siamo      # For Italian
/quienes-somos  # HEY!! WHAT HERE? es_ES or es_MX???
/who-we-are     # the same => en_US or en_GB?

They need "host" qualification.
Dynamic routes problems
Also, when the route matches /{destination} or /{destination}/{trip} I want to explore only a subset of the destinations:
If I'm in example.mx and I get /tailandia/circuito-sur-norte I don't need to explore the full destination list in all the languages, and all the trips; only the Spanish es_MX seo-friendly destinations and trips.
Similarly, if I'm in example.co.uk and I get /thailand/circuit-south-north I need only to explore the en_GB seo-titles to get what to render.
Strategies thought up to now
I have thought 2 strategies that could work:
a) Routing YML strategy
In the routing.yml have some kind of "rule" related to the "host" and set the "_locale" param by hand, something similar to:
whoWeAre_es_ES:
    path: /quienes-somos
    methods: [ GET ]
    host: example.es
    defaults:
        _controller: CatalogBundle:Legal:whoWeAre
        _locale: es_ES

whoWeAre_es_MX:
    path: /quienes-somos
    methods: [ GET ]
    host: example.mx
    defaults:
        _controller: CatalogBundle:Legal:whoWeAre
        _locale: es_MX

NOTE/DOUBT: I don't know if that "host" thing there would actually affect the route matcher or it is only for building routes.
In addition, this creates a problem when generating the routes. If in the home page I'm placing a link to the whoWeAre I should be knowing what of those routes to render and yields me in some kind of spaghetti code which is undesired.
b) Deployer strategy
Have multiple routing.yml files and tune the inclusion in the deployer:
src/CatalogBundle/Resources/config/routing_es_ES.yml
src/CatalogBundle/Resources/config/routing_es_MX.yml
src/CatalogBundle/Resources/config/routing_en_GB.yml
src/CatalogBundle/Resources/config/routing_en_US.yml

Then in the deployer, use a sed over the file
app/config/routing.yml

and include one or other of the routing files in function of the domain I am currently deploying.
I like this approach as each domain will have it's own "auto-contained" routing definition; and it also allows me to set the locale for the full site as a setting in the config.yml like this:
parameters:
    locale: en_GB

Instead, this creates ugly duplication. For example, all the general matching routes like /{destination}/{trip} will be duplicated in all the routing files.
Okey, I could extract them common factor to aother file which is included by all of them.
Common problems to both approaches
Still the static routes only differentiate in setting the _locale thing but share the _controller part.
I don't know if it is possible for a route in symfony to add a default parameter and then forward the matcher to another named route, like for example:
whoWeAre_es_ES:
    path: /quienes-somos
    host: example.es
    defaults:
        _locale: es_ES
    someKindOfReroutingThingPointingTo: whoWeAre

whoWeAre_es_MX:
    path: /quienes-somos
    host: example.mx
    defaults:
        _locale: es_MX
    someKindOfReroutingThingPointingTo: whoWeAre

whoWeAre_en_GB:
    path: /who-we-are
    host: example.co.uk
    defaults:
        _locale: es_MX
    someKindOfReroutingThingPointingTo: whoWeAre

whoWeAre:
    methods: [ GET ]
    defaults:
        _controller: CatalogBundle:Legal:whoWeAre

So... Questions

*

*Is any of those two solutions something that I should go for?

*Anyone has tried any of those and has a list of objective pros-cons?

*What's the best documented best-practice routing strategy for multi-domain localization of a SF3 application?

*Is it possible for a routing definition to add some parameters and then switch to another routing rule that has common things?

Thnkx!


text:
Q: SQLite - add new itens to result I'm using cordova SQLite storage plugin in my application Android. I need get result from 2 tables to display in view, my tables are "posts" and "metas"...
So I can publish 'products' (posts table) and informations like price and color are save in metas table. The problem is when I need show metas from products, I need list and after get information from table metas, but I need add metas in principal result (from first query).
Actually is returned
    results.rows.item(i).id
    results.rows.item(i).title
    results.rows.item(i).date

and I want add others items like this
    results.rows.item(i).id
    results.rows.item(i).title
    results.rows.item(i).date
    results.rows.item(i).price
    results.rows.item(i).color

But don't know how to do this, can you help me?
This is my functions...
function query( sql, callback ){

    db.transaction(function(transaction) {

        var executeQuery = sql;
        transaction.executeSql(executeQuery, [ ],
        function(tx, result) {
            //Success

            if( typeof( callback ) == 'function' ){
                callback( result );
            }
        },
        function(error){
            // Error
        });
    }
}

function get_meta( data, strMetaKey, callback ){

    for( i=0; i < data.length; i++ ){

        // QUERY
        query( /* SQL WHERE id = i.id AND meta_key = strMetaKey*/, function( result ){

            // here is my problem, I can't add 'price' to data
            data.rows.item( i ).price = result.rows.item(0).meta_value;
        });

    }

    if( typeof( callback ) == 'function' ){
        callback( data );
    }
}

new_data = '';

// getting products
query( /* my query */, function( result ){

    // getting price
    get_meta( result, 'price', function( result ){
        new_data = result;
    });

    // getting color
    get_meta( result, 'color', function( result ){
        new_data = result;
    });
});

Database schema
posts
ID
title
date
type

metas
id
meta_key
meta_value

A: To add specific meta keys to a query on the main table, you can use correlated subqueries to look the values up:
SELECT ID,
       title,
       date,
       (SELECT meta_value
        FROM metas
        WHERE id       = posts.id
          AND meta_key = 'price'
       ) AS price,
       (SELECT meta_value
        FROM metas
        WHERE id       = posts.id
          AND meta_key = 'color'
       ) AS color
FROM posts;


text:
Q: Getting windows domain name I need to get the Windows domain name from Internet Explorer using classic asp (I could try it in another way if with classic asp it's not possible).
I need to do this in order to insert the domain name into a database row.
So again, in summary, I need to retrieve the Windows computer domain name from the Internet Explorer that is accessing to a particular webpage.
Any idea where I could find and example in order to do that?, is it possible?

A: Web browsers by default use the web protocols (think Http, Html, Ssl, etc.). By your username I know that you are familiar with the RFCs that define these protocols.
Windows networks use a different protocols. The Domain is a logical security boundary in Windows networks. Yes, in modern versions of Windows Domain security uses standard protocols like Kerberos.
The problem you'll have is that a web browser doesn't normally send extra information to a web server about the client. That would be a huge security problem. So, by default a web browser (even IE) would not volunteer any network security information in an Http request.
When your web server requires client authentication, the web browser then must provide more security information to the server. Depending on the type of authentication your web server requires, your browser will send different information. For instance, in Http Basic authentication, the browser will send a username and password.
To my knowledge, the best way to get Windows Network Domain information from a web browser is to force the browser to authenticate using Windows Authentication. This is a special authentication mode that Microsoft built that pushes Microsoft network security information over the standard Http protocol. However, in order for this to work:

*

*Users must be running IE on Windows

*Web server must be IIS on Windows

*The client and server must have a Windows security relationship

*IIS must be enabled for Windows Auth

*There are many restrictions about the network path between the client and the server. Proxies and firewalls will typically prevent the IE Client from using windows authentication with IIS.

If you can live with this checklist, I think you will find the domain info in the one of the http headers. You may have to parse it out of the username which will be domain\user. But I'm sorry I don't remember the specifics. This should work even in classic ASP. More info on Windows Authentication is available at http://www.iis.net/ConfigReference/system.webServer/security/authentication/windowsAuthentication
http://msdn.microsoft.com/en-us/magazine/cc301387.aspx is about ASP.NET, but it says:

For a user authenticated using Windows
  authentication, the name is of the
  form domainname\username, where
  domainname is the name of the domain
  in which the user is registered (or
  machine name if it's a local account
  instead of a domain account), and
  username is the user's name.

In Classic ASP, try Request.ServerVariables ("AUTH_USER") or Request.ServerVariables ("LOGON_USER")
One alternative to Windows Authentication is to use Basic Auth and force the user to login with their windows credentials as domain\user. This however presents other security issues and you should do this only over SSL. However, this technique will work over the Internet and doesn't require a security relationship between the client PC and the server. This would also work for non-IE browsers.

A: In case anyone happens to get the same problem, here is the solution I've implemented (pretty much what Michael Levy said).
You have to activate Integrated Windows Authentication in IIS: http://en.wikipedia.org/wiki/Integrated_Windows_Authentication.
You can read here how to do it: http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5f8fe119-4095-4094-bba5-7dec361c7afe.mspx?mfr=true
After that you can use:

In Classic ASP Request.ServerVariables
  ("AUTH_USER") or
  Request.ServerVariables ("LOGON_USER")

It seems to work also with other browsers, not only with IE.
Thanks again to Michael Levy to point me in the right direction.


text:
Q: Trying to get JavaScript code completion to work in netbeans with jsdoc In my app.js I have the following:
angular.module('app').controller('userList',
  ['appSettings'
 ,function (/*@type {app.appSettings}*/appSettings) {
   appSettings.<<== it shows a list here but nothing from autocomplete.js

In my autocomplete.js I have the following (generated by JavaScript printing out my services and their members):
var app={};
app.appSettings={};
app.appSettings.userFailMessages={};
app.appSettings.userFailMessages.invalidJson
  ="Invalid request, user sent is not valid json.";

NetBeans refuses to code complete appSettings for me and doesn't seem to know it's defined in autocomplete.js. Maybe I'm getting my js doc wrong but tried a mix of combination of @var, @type and @param without success.
It code completes when I type app.appSettings. and gives me a list from autocomplete.js but I would like to know how I can tell NetBeans that the passed argument to the function is app.appSettings.
Maybe I should have autocomplete contain constructor functions instead of object literals as @type suggests a certain type and not an instance.
This is NetBeans 7.3.1

A: Was close to the answer, to have NetBeans use type you have to define the type. Then to indicate that the parameters passed to your angular module (or any function) are of a certain type I use the @param jsdoc
The angular module:
angular.module('app').controller('userList'
 , ['$scope','appRules','appSettings'
 ,/**
* @param {app.appRules} appRules
* @param {app.appSettings} appSettings
* */
 function ($scope,appRules,appSettings,$timeout) {
   //<== here both appRules and appSettings give suggestions
   //  from autocomplete

autocomplete.js (not included in my html file but just there for code suggest)
/*@typedef {Object} app*/
var app={};
app.appRules={};
app.appRules.userIsInRole=function (user,role){};
app.appRules.general={};
app.appRules.general.isEmpty=function (val){};
app.appRules.general.isEmail=function (val){};
app.appSettings={};
app.appSettings.userFailMessages={};
app.appSettings.userFailMessages.invalidJson
 ="Invalid request, user sent is not valid json.";
app.appSettings.userFailMessages.noPrivilege
 ="You do not have the privileges needed to change this user.";

I ran the following code in the console on a page that contains my app to generate autocomplete.js:
var inj;
function allServices(mod, r) {
  if (!r) {
    r = {};
    inj = angular.element(document.querySelector('[data-ng-app]')).injector().get;
  }
  angular.forEach(angular.module(mod).requires, function(m) {
    allServices(m, r)
  });
  angular.forEach(angular.module(mod)._invokeQueue, function(a) {
    try {
      r[a[2][0]] = inj(a[2][0]);
    } catch (e) {
    }
  });
  return r;
};

var output=[];
function addOutput(names,prop){
  if(names.length===1){
    output.push('var ');
  }
  output.push(names.join('.'));
  if(typeof prop === 'object'){
    output.push('={};\n');
    for(thing in prop){
      //TODO: no arrays or route paths
      if(/[0-9\/\\]/.test(thing)){
        continue;
      }
      names.push(thing);
      addOutput(names,prop[thing]);
    }
  }else{
    output.push('=');
    output.push(
      (typeof prop === 'function')?
      prop.toString():
      JSON.stringify(prop)
    );
    output.push(';\n');
  }
  names.pop();
}

function createOutput(){
  allMyServices = allServices('app');
  addOutput(['app'],allMyServices);
  console.log(output.join(''));
}

createOutput();


text:
Q: Segmentation Fault (core dump) in terminal but no in Xcode So when i run this code in my IDE(xCode) I have no issues, once i try to run it with gcc compiler I get a Segmentation Fault (core dump) error. not really sure where I am going wrong. The program is suppose to read in a text file and justify the text according to the users set line length. it also takes into account if a new paragraph was started and prints the text out with the correct justification.
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>

struct listNode {  /* self-referential structure */
   char *data;
   struct listNode *nextPtr;
};

typedef struct listNode LISTNODE;
typedef LISTNODE *LISTNODEPTR;

void insert(LISTNODEPTR *, char *);
char delete(LISTNODEPTR *, char *);
int isEmpty(LISTNODEPTR);
void printList(LISTNODEPTR, int);
void instructions(void);
void freeMemory(LISTNODEPTR);

int lineLength;
char filename[100];

int main(){

   FILE *filePonter = NULL;
   LISTNODEPTR startPtr = NULL;

   instructions();

   if((filePonter = fopen(filename, "r")) == NULL){

      printf("File can not be open. \n");
      exit(1);
   }else{
     char *item = malloc(30*sizeof(char));
     char *str = malloc(BUFSIZ);
     char *data = malloc(30*sizeof(char));
     item = fgets(item, BUFSIZ,filePonter);
     while(item != NULL){
        while(item != NULL && strncmp(item, "\r\n",2)){
            strcat(str, item);
            //printf("%s", str);
            item = fgets(item, BUFSIZ,filePonter);
        }
        if(strncmp(str,"",1)){
            data = strtok(str," \n");
            while(str != NULL && data != NULL){

                insert(&startPtr, data);
                data = strtok(NULL, " \r\n");
                //printf("%s", data);

            }
            free(data);
            str = malloc(BUFSIZ);
            printList(startPtr,lineLength );
            //freeMemory(startPtr);
            startPtr = NULL;
            printf("\n");

        }
        item = fgets(item, BUFSIZ,filePonter);
    }
}

return 0;
}

/* Print the instructions */
void instructions(void)
{
  lineLength = 0;
  while(lineLength < 40 || lineLength > 100){
    printf("Please enter the number of characters per line.\n");
    printf("Valid lengths are between 40 and 100. \n");
    scanf("%d", &lineLength);
  }

  printf("Please enter the file name. \n");
  scanf("%s", filename);

}

/* Insert a new value into the list in sorted order */
void insert(LISTNODEPTR *sPtr, char *value)
{
  LISTNODEPTR newPtr, previousPtr, currentPtr;

  newPtr = malloc(30*sizeof(LISTNODE));

  if (newPtr != NULL) {    /* is space available */
    newPtr->data = value;
    newPtr->nextPtr = NULL;

    previousPtr = NULL;
    currentPtr = *sPtr;

    while (currentPtr != NULL && value > currentPtr->data) {
        previousPtr = currentPtr;          /* walk to ...   */
        currentPtr = currentPtr->nextPtr;  /* ... next node */
    }

    if (previousPtr == NULL) {
        newPtr->nextPtr = *sPtr;
        *sPtr = newPtr;
    }
    else {
        previousPtr->nextPtr = newPtr;
        newPtr->nextPtr = currentPtr;
      }
  }
  else
    printf("%s not inserted. No memory available.\n", value);
}

/* Delete a list element */
char delete(LISTNODEPTR *sPtr, char *value)
{
  LISTNODEPTR previousPtr, currentPtr, tempPtr;

  if (value == (*sPtr)->data) {
    tempPtr = *sPtr;
    *sPtr = (*sPtr)->nextPtr;  /* de-thread the node */
    free(tempPtr);             /* free the de-threaded node */
    return *value;
  }
  else {
    previousPtr = *sPtr;
    currentPtr = (*sPtr)->nextPtr;

    while (currentPtr != NULL && currentPtr->data != value) {
        previousPtr = currentPtr;          /* walk to ...   */
        currentPtr = currentPtr->nextPtr;  /* ... next node */
    }

    if (currentPtr != NULL) {
        tempPtr = currentPtr;
        previousPtr->nextPtr = currentPtr->nextPtr;
        free(tempPtr);
        return *value;
    }
  }

  return '\0';
 }

 /* Print the list */
 void printList(LISTNODEPTR currentPtr, int length)
{
  LISTNODEPTR end = currentPtr;
  LISTNODEPTR aPtr = currentPtr;
  LISTNODEPTR begin = currentPtr;

  while(begin->nextPtr != NULL)
  {
    int numSpace[80] = {};
    int NumWSpace = 0;
    int charLine = 0;
    int leftOverSpace = 0;
    int counter = 0;
    int finalLine = 0;
    int j = 0;
    int i = 0;

    charLine = strlen(end->data)+1;
    counter = 1;
    end = end->nextPtr;

    while(charLine+strlen(end->data)+1 < length)
    {
        charLine = charLine + strlen(end->data) + 1;
        counter = counter + 1;
        if(end->nextPtr != NULL)
            end = end->nextPtr;
        else
        {
            finalLine = 1;
        }
    }
    leftOverSpace = length - (charLine-1);

    while(leftOverSpace > 0)
    {
        if(NumWSpace < (counter - 1))
        {
            numSpace[NumWSpace] = numSpace[NumWSpace] + 1;
            leftOverSpace = leftOverSpace - 1;
            NumWSpace = NumWSpace + 1;
        }
        else
            NumWSpace = 0;
    }

    /*This loop will print out the words for the line it is on*/

    for( i = 1; i <= counter; i++)
    {
        if(i < counter)
        {
            printf("%s ", aPtr->data);
            for(j = 1; j <= numSpace[i-1]; j++)
            {
                printf(" ");
            }
        }
        else if(i == counter)
        {
            printf("%s\n", aPtr->data);
        }
        if(aPtr->nextPtr != NULL)
            aPtr = aPtr->nextPtr;
        else
            break;
    }
    if(aPtr->nextPtr != NULL)
        end = aPtr;
    if(end->nextPtr == NULL)
        begin = end;
    //printf("\n");
  }
}
void freeMemory(LISTNODEPTR startPtr)//Does not work
{
  LISTNODEPTR temp;

  while(startPtr->nextPtr != NULL)
  {
     temp = startPtr->nextPtr;
    free(startPtr->data);
    free(startPtr);
    startPtr = temp;
  }

}

text that is in the file
The President shall be Commander in Chief of the Army and Navy of the United States, and of the Militia of the several States, when called into
the actual Service of the United States; he may require the Opinion, in writing, of the principal
Officer in each of the executive Departments, upon any subject relating to the Duties of their respective Offices,
and he shall have Power to Grant Reprieves and Pardons for Offenses against The United States, except in Cases of Impeachment.

A: The Problem is here:
 // Here you allocate 30 chars
 char *item = (char *)malloc(30*sizeof(char));

 // and some lines below you read upto BUFSIZ chars
 item = fgets(item, BUFSIZ,filePonter);

BUFSIZ is 512 on my platform.
But there are probably more issues in your code. For example this is highly suspicious. Whats that magic number 30?
newPtr = malloc(30*sizeof(LISTNODE));


text:
Q: python webspider different between etree.ElementTree etree.fromstring etree.HTMLParser What function they are?
etree.HTMLParser()
etree.fromstring()
etree.ElementTree()

what different between
etree.fromstring(text, etree.HTMLParser())
etree.HTML(text)


text:
Q: How mySQL Update multiple tables query work? I would like to know the working of MySQL UPDATE table1 [,tables] SET col1=val1[,cols] query.
Also, how is it different from UPDATE tables with JOIN query?

A: Try this
UPDATE T1, T2,
[INNER JOIN | LEFT JOIN] T1 ON T1.C1 = T2. C1
SET T1.C2 = T2.C2,
    T2.C3 = expr
WHERE condition


text:
Q: PHP nodeValue and Character count I have a String variable containing text file (such as .html) using fopen()
and next im going to strip_tags() so that i can use that untaged text for an article preview, but before that, I need to get h1 nodeValue, and as well count characters of it, so i can replace the zero in the code below with that value, and end with 150+ that value.
$f = fopen($filepath,"r");
$WholeFile = fread($f, filesize($filepath));
fclose($f);
$StrippedFile=strip_tags($WholeFile);
$TextExtract = mb_substr("$StrippedFile", 0,150);

What is the best way for me to go?
Is a parser the answer? Since this is only situation [so far] I will be extracting values from html tags

A: When you have structured text (like HTML, XML, json, YAML, whatever), you should always use a proper parser unless you have a very good reason not to.
You might be able to get away with regexes in this situation, but you will have a very brittle solution and are likely to have problems related to character encoding, entities, or whitespace. All the solutions above will break subtly. For example, if you have input like this:
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Page title</title>

Title —    maybe emdash counted as 7 characters

 and      whitespace counted excessively too. And here's
a utf-8 character that may get split in the middle: ©; creating
an invalid string.

Here is a solution using DOMDocument and DOMXPath which should work on all but the worst HTML, and will always give you a 150 character (not byte, character) utf-8 reply with all entities normalized down to their character value.
$html = '<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Page title</title>

Title —    maybe emdash counted as 7 characters

 and      whitespace counted excessively too. And here\'s
a utf-8 character that may get split in the middle: ©; creating
an invalid string.

';

$doc = new DOMDocument();
$doc->loadHTML($html);
// if you have a url or filename, you can use this instead:
// $doc->loadHTMLFile($url);
$xp = new DOMXPath($doc);

// you can easily modify the xquery to match the "title" of different documents
$titlenode = $xp->query('/html/body//h1[1]');

$xpath = 'normalize-space(substring(
        concat(
            normalize-space(.),
            " ",
            normalize-space(./following-sibling::*)
        ), 0, 150))';

$excerpt = null;
if ($titlenode->length) {
    $excerpt = $xp->evaluate($xpath, $titlenode->item(0));
}

var_export($excerpt);

This code will output:
'Title — maybe emdash counted as 7 characters and whitespace counted excessively too. And here\'s a utf-8 character that may get split in the middle: ©'

The basic idea here is to match your h1 (or whatever title element) with XPath, then get the string value of that element and all following elements and truncate by 150 characters, also using XPath.  Keeping everything in XPath avoids all the messy charset and entity issues you would have to handle with PHP instead.

A: If you are certain of the content of the file you are processing, and know that the title is in H1, you could potentially slice the string you are getting at the

 location (using strstr() for example although there are a plethora of ways to do that), into two strings.
You can then strip tags on the first one to get the title and strip tags on the second one to get the content. This is assuming your file ONLY has a single h1 containing the title, before the dom element that contains the content of the article.
Keep in mind this is not the best way to parse a wide range of articles online, for a more general solution I'd look into a dedicated parser class.
Here is a code sample :
Code sample
$f = fopen($filepath,"r");
$WholeFile = fread($f, filesize($filepath));
fclose($f);
// Modified part
$content = strip_tags(strstr($WholeFile, '
'));
$title = strip_tags(strstr($WholeFile, '
', true)); // Valid with PHP 5.3.0 only I think
$TextExtract = mb_substr($content, 0,150);