问:
can attributes be hidden in a simplexmlobject?
I have this simplexml object and it looks fine, but when i convert a part of it... like:
$xmlMeshHeading = $MeshHeading->asXML();

I suddenly get attributes which i can't find in the simple XML object...?
Here are some parts of the two files:

```<code>SimpleXMLObject:

[MeshHeadingList] => SimpleXMLElement Object [DescriptorName] => Acoustic Stimulation
                                (
                                    [MeshHeading] => Array
                                        (
                                            [0] => SimpleXMLElement Object
                                                (

                                                    [QualifierName] => methods
                                                )

                                            [1] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Adolescent
                                                )

                                            [2] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Age Factors
                                                )

                                            [3] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Child
                                                )

                                            [4] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Electromyography
                                                    [QualifierName] => methods
                                                )

                                            [5] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Female
                                                )

                                            [6] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Galvanic Skin Response
                                                    [QualifierName] => physiology
                                                )

                                            [7] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Humans
                                                )

                                            [8] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Male
                                                )

                                            [9] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Muscle, Skeletal
                                                    [QualifierName] => physiology
                                                )

                                            [10] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Probability
                                                )

                                            [11] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Reaction Time
                                                    [QualifierName] => physiology
                                                )

                                            [12] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Sex Factors
                                                )

                                            [13] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Startle Reaction
                                                    [QualifierName] => physiology
                                                )
</code>```

And here the asXML file it's from the same source...:

```<code> <MeshHeadingList>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Acoustic Stimulation</DescriptorName>
                <QualifierName MajorTopicYN="N">methods</QualifierName>
            </MeshHeading>

            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Adolescent</DescriptorName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Age Factors</DescriptorName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Child</DescriptorName>

            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Electromyography</DescriptorName>
                <QualifierName MajorTopicYN="Y">methods</QualifierName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Female</DescriptorName>

            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Galvanic Skin Response</DescriptorName>
                <QualifierName MajorTopicYN="N">physiology</QualifierName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Humans</DescriptorName>

            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Male</DescriptorName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Muscle, Skeletal</DescriptorName>
                <QualifierName MajorTopicYN="Y">physiology</QualifierName>

            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Probability</DescriptorName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Reaction Time</DescriptorName>
                <QualifierName MajorTopicYN="N">physiology</QualifierName>

            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Sex Factors</DescriptorName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Startle Reaction</DescriptorName>
                <QualifierName MajorTopicYN="Y">physiology</QualifierName>

            </MeshHeading>
        </MeshHeadingList>
</code>```

My question is...
1. Is there a function to "unhide" the attributes in SimpleXML?
OR
2. How can i get stuff from an XML file, like attributes and the values...?

Best,
Thijs

答:
print_r() is simply not the right tool to inspect SimpleXMLElement objects.

If you want to know what's inside of one, just use ->asXML() on it and read it in XML. 100% of its nodes and attributes are always available despite not being displayed by print_r() or var_dump().

Body:
I have this simplexml object and it looks fine, but when i convert a part of it... like:
$xmlMeshHeading = $MeshHeading->asXML();

I suddenly get attributes which i can't find in the simple XML object...?
Here are some parts of the two files:

SimpleXMLObject:

[MeshHeadingList] => SimpleXMLElement Object [DescriptorName] => Acoustic Stimulation
                                (
                                    [MeshHeading] => Array
                                        (
                                            [0] => SimpleXMLElement Object
                                                (

                                                    [QualifierName] => methods
                                                )

                                            [1] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Adolescent
                                                )

                                            [2] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Age Factors
                                                )

                                            [3] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Child
                                                )

                                            [4] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Electromyography
                                                    [QualifierName] => methods
                                                )

                                            [5] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Female
                                                )

                                            [6] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Galvanic Skin Response
                                                    [QualifierName] => physiology
                                                )

                                            [7] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Humans
                                                )

                                            [8] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Male
                                                )

                                            [9] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Muscle, Skeletal
                                                    [QualifierName] => physiology
                                                )

                                            [10] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Probability
                                                )

                                            [11] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Reaction Time
                                                    [QualifierName] => physiology
                                                )

                                            [12] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Sex Factors
                                                )

                                            [13] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Startle Reaction
                                                    [QualifierName] => physiology
                                                )

And here the asXML file it's from the same source...:

 <MeshHeadingList>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Acoustic Stimulation</DescriptorName>
                <QualifierName MajorTopicYN="N">methods</QualifierName>
            </MeshHeading>

            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Adolescent</DescriptorName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Age Factors</DescriptorName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Child</DescriptorName>

            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Electromyography</DescriptorName>
                <QualifierName MajorTopicYN="Y">methods</QualifierName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Female</DescriptorName>

            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Galvanic Skin Response</DescriptorName>
                <QualifierName MajorTopicYN="N">physiology</QualifierName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Humans</DescriptorName>

            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Male</DescriptorName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Muscle, Skeletal</DescriptorName>
                <QualifierName MajorTopicYN="Y">physiology</QualifierName>

            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Probability</DescriptorName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Reaction Time</DescriptorName>
                <QualifierName MajorTopicYN="N">physiology</QualifierName>

            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Sex Factors</DescriptorName>
            </MeshHeading>
            <MeshHeading>
                <DescriptorName MajorTopicYN="N">Startle Reaction</DescriptorName>
                <QualifierName MajorTopicYN="Y">physiology</QualifierName>

            </MeshHeading>
        </MeshHeadingList>

My question is...
1. Is there a function to "unhide" the attributes in SimpleXML?
OR
2. How can i get stuff from an XML file, like attributes and the values...?

Best,
Thijs


来源: stackexchange

问:
Angular 2 : Validators, ReactiveForms, FormBuilder and custom classes
Let's say you have this class

```<code>export class User {
    username = '';
    password = '';
}
</code>```

When you make a reactive form, you can do it like this

```<code>this.userForm = this.fb.group({
    username: ''
    password: ''
});
</code>```

Or, second way

```<code>this.userForm = this.fb.group(new User());
</code>```

My problem comes with the second way : when you use the first way, you can add Validators to your controls like this

```<code>username: ['', Validators.required],
password: ['', Validators.required]
</code>```

But with the second way, how can you add Validators to your form controls ?

答:
Try</p>

```<code>let control = this.form.controls["username"];
let newValidators = Validators.compose([Validators.required, Validators.minLength(8), Validators.maxLength(255)])
control.setValidators(newValidators);
control.updateValueAndValidity();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Let's say you have this class

export class User {
    username = '';
    password = '';
}

When you make a reactive form, you can do it like this

this.userForm = this.fb.group({
    username: ''
    password: ''
});

Or, second way

this.userForm = this.fb.group(new User());

My problem comes with the second way : when you use the first way, you can add Validators to your controls like this

username: ['', Validators.required],
password: ['', Validators.required]

But with the second way, how can you add Validators to your form controls ?

Body:
Try

let control = this.form.controls["username"];
let newValidators = Validators.compose([Validators.required, Validators.minLength(8), Validators.maxLength(255)])
control.setValidators(newValidators);
control.updateValueAndValidity();


问:
python: zipping csv buffers
I want to zip some csv buffers into a new zip buffer as follows (python 2.7):

```<code>files = []

csv_buffer = StringIO.StringIO()
writer = csv.writer(csv_buffer)
writer.writerow(["some", "csv", "data"])

csv_buffer.seek(0)

files.append(csv_buffer)

zipped_file = io.BytesIO()

with zipfile.ZipFile(zipped_file, 'w') as zipper:
    for i, csv_file in enumerate(files):
        csv_file.seek(0)
        zipper.writestr("{}.csv".format(i), csv_file.read())

zipped_file.seek(0)
</code>```

Then I dispatch the resulting buffer through a Django view to download. However if I open the zip, I find a file (0.csv), but it is not correctly encoded. I would like to have it encoded as UTF-8.

I tried also as follows:

```<code>zipper.writestr("{}.csv".format(i), csv_file.read().encode("utf-8"))
</code>```

but that made no difference. Also changing

```<code>zipped_file = io.BytesIO()
</code>```

to

```<code>zipped_file = StringIO.StringIO()
</code>```

Didn't help.
Any ideas about what went wrong would be much appreciated!

EDIT: My Solution

Despite the otherwise helpful and interesting answers hereunder I solved the problem by changing

```<code>    zipper.writestr("{}.csv".format(i), csv_file.read())
</code>```

to

```<code>     zipper.writestr(zipfile.Zipinfo("foo.csv"), csv_file.read())
</code>```

Dont know why, but that made it work

答:
So, it seems you are not encoding your CSV properly.

Take a look at this note in the csv module docs (Python 2.7):

Note This version of the csv module doesn’t support Unicode input. Also, there are currently some issues regarding ASCII NUL characters. Accordingly, all input should be UTF-8 or printable ASCII to be safe; see the examples in section Examples.

This is the example they are referring to:

```<code>class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([s.encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)
</code>```

Just use UnicodeWriter instead of csv.writer (a drop-in replacement):

```<code>writer = UnicodeWriter(csv_buffer)
</code>```

instead of:

```<code>writer = csv.writer(csv_buffer)
</code>```

Or, if you can, switch to Python 3 which handles Unicode much better than Python 2.

Title: python: zipping csv buffers

Body:
I want to zip some csv buffers into a new zip buffer as follows (python 2.7):

files = []

csv_buffer = StringIO.StringIO()
writer = csv.writer(csv_buffer)
writer.writerow(["some", "csv", "data"])

csv_buffer.seek(0)

files.append(csv_buffer)

zipped_file = io.BytesIO()

with zipfile.ZipFile(zipped_file, 'w') as zipper:
    for i, csv_file in enumerate(files):
        csv_file.seek(0)
        zipper.writestr("{}.csv".format(i), csv_file.read())

zipped_file.seek(0)

Then I dispatch the resulting buffer through a Django view to download. However if I open the zip, I find a file (0.csv), but it is not correctly encoded. I would like to have it encoded as UTF-8.

I tried also as follows:

zipper.writestr("{}.csv".format(i), csv_file.read().encode("utf-8"))

but that made no difference. Also changing

zipped_file = io.BytesIO()

to

zipped_file = StringIO.StringIO()

Didn't help.
Any ideas about what went wrong would be much appreciated!

EDIT: My Solution

Despite the otherwise helpful and interesting answers hereunder I solved the problem by changing

    zipper.writestr("{}.csv".format(i), csv_file.read())

to

     zipper.writestr(zipfile.Zipinfo("foo.csv"), csv_file.read())

Dont know why, but that made it work

Body:
So, it seems you are not encoding your CSV properly.

Take a look at this note in the csv module docs (Python 2.7):

Note This version of the csv module doesn’t support Unicode input. Also, there are currently some issues regarding ASCII NUL characters. Accordingly, all input should be UTF-8 or printable ASCII to be safe; see the examples in section Examples.

This is the example they are referring to:

class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([s.encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

Just use UnicodeWriter instead of csv.writer (a drop-in replacement):

writer = UnicodeWriter(csv_buffer)

instead of:

writer = csv.writer(csv_buffer)

Or, if you can, switch to Python 3 which handles Unicode much better than Python 2.


问:
Restore database from pg_dump
I had non-empty db and made backup it by:

pg_dump myBase > backup.sql

Then I must to delete db and now I am trying to restore it from backup.sql. So first I create database by:

create database myBase

grant privileges from psql

grant all privileges on database "myBase" to myUser

and then trying to recover from pg_dump by:

pg_dump myBase < backup.sql

And I didn't get any errors, but when I check tables by \dt it's totally empty.
I have also tried restoring with:

psql -h localhost -d myBase-U myUser-f backup.sql (no error, but no tables too)

psql myBase < backup.sql (like above)

I have a little expieriences with dbs so I assume it should be something obvious for more experienced user.

答:
Can't reproduce the issue:</p>

```<code>postgres=# create database so;
CREATE DATABASE
postgres=# \c so
You are now connected to database "so" as user "postgres".
so=# create table so(i int);
CREATE TABLE
so=# insert into so values (1);
INSERT 0 1
so=# \! pg_dump so > /tmp/so.sql
so=# \c postgres
You are now connected to database "postgres" as user "postgres".
postgres=# drop database so;
DROP DATABASE
postgres=# create database so;
CREATE DATABASE
postgres=# \c so
You are now connected to database "so" as user "postgres".
so=# \dt
No relations found.
so=# \! psql so -f /tmp/so.sql
SET
SET
SET
SET
SET
SET
CREATE EXTENSION
COMMENT
SET
SET
SET
CREATE TABLE
ALTER TABLE
REVOKE
REVOKE
GRANT
GRANT
so=# \dt
        List of relations
 Schema | Name | Type  |  Owner
--------+------+-------+----------
 public | so   | table | postgres
(1 row)
</code>```

Title: Restore database from pg_dump

Body:
Can't reproduce the issue:

postgres=# create database so;
CREATE DATABASE
postgres=# \c so
You are now connected to database "so" as user "postgres".
so=# create table so(i int);
CREATE TABLE
so=# insert into so values (1);
INSERT 0 1
so=# \! pg_dump so > /tmp/so.sql
so=# \c postgres
You are now connected to database "postgres" as user "postgres".
postgres=# drop database so;
DROP DATABASE
postgres=# create database so;
CREATE DATABASE
postgres=# \c so
You are now connected to database "so" as user "postgres".
so=# \dt
No relations found.
so=# \! psql so -f /tmp/so.sql
SET
SET
SET
SET
SET
SET
CREATE EXTENSION
COMMENT
SET
SET
SET
CREATE TABLE
ALTER TABLE
REVOKE
REVOKE
GRANT
GRANT
so=# \dt
        List of relations
 Schema | Name | Type  |  Owner
--------+------+-------+----------
 public | so   | table | postgres
(1 row)


问:
How do I toggle an element's class in pure JavaScript?
I'm looking for a way to convert this jQuery code (which is used in responsive menu section) to pure JavaScript.

If it's hard to implement it's OK to use other JavaScript frameworks.

```<code>$('.btn-navbar').click(function()
{
    $('.container-fluid:first').toggleClass('menu-hidden');
    $('#menu').toggleClass('hidden-phone');

    if (typeof masonryGallery != 'undefined')
        masonryGallery();
});
</code>```

答:
Here is a code for IE >= 9 by using split(" ") on the className :</p>

```<code>function toggleClass(element, className) {
    var arrayClass = element.className.split(" ");
    var index = arrayClass.indexOf(className);

    if (index === -1) {
        if (element.className !== "") {
            element.className += ' '
        }
        element.className += className;
    } else {
        arrayClass.splice(index, 1);
        element.className = "";
        for (var i = 0; i < arrayClass.length; i++) {
            element.className += arrayClass[i];
            if (i < arrayClass.length - 1) {
                element.className += " ";
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm looking for a way to convert this jQuery code (which is used in responsive menu section) to pure JavaScript.

If it's hard to implement it's OK to use other JavaScript frameworks.

$('.btn-navbar').click(function()
{
    $('.container-fluid:first').toggleClass('menu-hidden');
    $('#menu').toggleClass('hidden-phone');

    if (typeof masonryGallery != 'undefined')
        masonryGallery();
});

Body:
Here is a code for IE >= 9 by using split(" ") on the className :

function toggleClass(element, className) {
    var arrayClass = element.className.split(" ");
    var index = arrayClass.indexOf(className);

    if (index === -1) {
        if (element.className !== "") {
            element.className += ' '
        }
        element.className += className;
    } else {
        arrayClass.splice(index, 1);
        element.className = "";
        for (var i = 0; i < arrayClass.length; i++) {
            element.className += arrayClass[i];
            if (i < arrayClass.length - 1) {
                element.className += " ";
            }
        }
    }
}


问:
Determine timezone based on location using Here APIs
I want to get get the timezone of a location (lat/long) using the here REST APIs.  I know there is a Google timezone API to do this, but I couldn't see any timezone information in any "Reverse Geocoding" API responses for the here REST APIs.</p>

答:
For reverse geocoding you need to add additional parameter locationattributes=tz to the request. Example request:

```<code>https://reverse.geocoder.cit.api.here.com/6.2/reversegeocode.json
?prox=50.112,8.683,100
&mode=retrieveAddresses
&app_id=xxx
&app_code=yyy
&gen=9
&locationattributes=tz
</code>```

You can find a full description of available input parameters by link: https://developer.here.com/rest-apis/documentation/geocoder/topics/resource-reverse-geocode.html

Body:
For reverse geocoding you need to add additional parameter locationattributes=tz to the request. Example request:

https://reverse.geocoder.cit.api.here.com/6.2/reversegeocode.json
?prox=50.112,8.683,100
&mode=retrieveAddresses
&app_id=xxx
&app_code=yyy
&gen=9
&locationattributes=tz

You can find a full description of available input parameters by link: https://developer.here.com/rest-apis/documentation/geocoder/topics/resource-reverse-geocode.html


问:
Gmail returns 534-5.7.14 Please log in via your web browser
I found this error while i'm trying to send an email from one Gmail account to another. How to solve this error ? Help me on it.

There were an error:

534-5.7.14 Please log in via your web browser and 534-5.7.14 then try again. 534-5.7.14 Learn more at 534 5.7.14 https://support.google.com/mail/answer/78754 hw7sm51688135pac.12 - gsmtp

答:
You need to allow less secure apps, you can do it by click below link

https://www.google.com/settings/security/lesssecureapps

also try this one

https://accounts.google.com/DisplayUnlockCaptcha

if still not works try changing password for gmail


问:
How would I implement this fold function?
Given are the two datatypes Color and Plant.

```<code>data Color = Red | Pink | White | Blue | Purple | Green | Yellow
   deriving (Show, Eq)

data Plant =
     Leaf
   | Blossom Color
   | Stalk Plant Plant
   deriving (Show, Eq)
</code>```

Now I'm supposed to implement a function fold_plant of following type:

```<code>(x -> x -> x) -> (Color -> x) -> x -> Plant -> x
</code>```

The way I understand a fold function is that it takes a list and for each iteration it removes the first element from the list and does something with that element.

Apparently fold_plant Stalk Blossom Leaf is the identity on plants.

Now I know that in Haskell you make functions like this:

```<code>fold_plant :: (x -> x -> x) -> (Color -> x) -> x -> Plant -> x
fold_plant = do something
</code>```

But from here on I don't know how a fold function would work an a plant.

答:
Folding is the essence of recursive problem solving:

```<code>    data <b>Plant</b> =                        data Result <b>r</b> =
         Leaf                                RLeaf
       | Blossom Color                     | RBlossom Color
       | Stalk <b>Plant Plant</b>                 | RStalk <b>r r</b>
            -- recursive data           -- non-recursive data: `r`, not `Result r`!</code>```

Recursive problem solving is about combining in a simple manner the results of recursively processing the constituents of the original structure:

```<code>    -- single-step reduction semantics:
    -- reduction_step :: ..... -> Result r -> r
    reduction_step :: (r -> r -> r) -> (Color -> r) -> r -> Result r -> r
    reduction_step s b <b>l</b>  RLeaf       = <b>l</b>
    reduction_step s <b>b</b> l (RBlosom c)  = <b>b</b> c
    reduction_step <b>s</b> b l (RStalk x y) = <b>s</b> x y</code>```

But to get to this point we need to recurse into the constituent parts of our original structure which are of the same nature as the whole structure, and thus the fold_plant procedure which we seek to create can be applied to them as if already written (recursion!):

```<code>    recurse_into :: (r -> r -> r) -> (Color -> r) -> r -> Plant -> Result r
    recurse_into s b l Leaf          = RLeaf
    recurse_into s b l (Blossom c)   = RBlossom c
    recurse_into s b l (Stalk <b>lt rt</b>) = RStalk (fold_plant s b l <b>lt</b>) (fold_plant s b l <b>rt</b>)</code>```

so, finally, our fold is simply a composition of the two,

```<code>    fold_plant :: (r -> r -> r) -> (Color -> r) -> r -> Plant -> r
    fold_plant s b l <b>plant</b> = reduction_step s b l          --          Result r -> r
                               (recurse_into s b l <b>plant</b>)  -- Plant -> Result r</code>```

Do follow the types and convince yourself that everything fits together as it should.

The interim data definition can of course be eschewed and the function definition collapsed, but this is the general procedure to follow.

(cf. recursion schemes).

Body:
Given are the two datatypes Color and Plant.

data Color = Red | Pink | White | Blue | Purple | Green | Yellow
   deriving (Show, Eq)

data Plant =
     Leaf
   | Blossom Color
   | Stalk Plant Plant
   deriving (Show, Eq)

Now I'm supposed to implement a function fold_plant of following type:

(x -> x -> x) -> (Color -> x) -> x -> Plant -> x

The way I understand a fold function is that it takes a list and for each iteration it removes the first element from the list and does something with that element.

Apparently fold_plant Stalk Blossom Leaf is the identity on plants.

Now I know that in Haskell you make functions like this:

fold_plant :: (x -> x -> x) -> (Color -> x) -> x -> Plant -> x
fold_plant = do something

But from here on I don't know how a fold function would work an a plant.

Body:
Folding is the essence of recursive problem solving:

    data Plant =                        data Result r =
         Leaf                                RLeaf
       | Blossom Color                     | RBlossom Color
       | Stalk Plant Plant                 | RStalk r r
            -- recursive data           -- non-recursive data: `r`, not `Result r`!

Recursive problem solving is about combining in a simple manner the results of recursively processing the constituents of the original structure:

    -- single-step reduction semantics:
    -- reduction_step :: ..... -> Result r -> r
    reduction_step :: (r -> r -> r) -> (Color -> r) -> r -> Result r -> r
    reduction_step s b l  RLeaf       = l
    reduction_step s b l (RBlosom c)  = b c
    reduction_step s b l (RStalk x y) = s x y

But to get to this point we need to recurse into the constituent parts of our original structure which are of the same nature as the whole structure, and thus the fold_plant procedure which we seek to create can be applied to them as if already written (recursion!):

    recurse_into :: (r -> r -> r) -> (Color -> r) -> r -> Plant -> Result r
    recurse_into s b l Leaf          = RLeaf
    recurse_into s b l (Blossom c)   = RBlossom c
    recurse_into s b l (Stalk lt rt) = RStalk (fold_plant s b l lt) (fold_plant s b l rt)

so, finally, our fold is simply a composition of the two,

    fold_plant :: (r -> r -> r) -> (Color -> r) -> r -> Plant -> r
    fold_plant s b l plant = reduction_step s b l          --          Result r -> r
                               (recurse_into s b l plant)  -- Plant -> Result r

Do follow the types and convince yourself that everything fits together as it should.

The interim data definition can of course be eschewed and the function definition collapsed, but this is the general procedure to follow.

(cf. recursion schemes).


问:
How CUDA box filter works?
I have this sample of code that I try to understand it:

```<code>    __global__ void
d_boxfilter_rgba_x(unsigned int *od, int w, int h, int r)
    {
    float scale = 1.0f / (float)((r << 1) + 1);
    unsigned int y = blockIdx.x*blockDim.x + threadIdx.x;

    if (y < h)
        {
        float4 t = make_float4(0.0f);

        for (int x = -r; x <= r; x++)
            {
            t += tex2D(rgbaTex, x, y);
            }

        od[y * w] = rgbaFloatToInt(t * scale);

        for (int x = 1; x < w; x++)
            {
            t += tex2D(rgbaTex, x + r, y);
            t -= tex2D(rgbaTex, x - r - 1, y);
            od[y * w + x] = rgbaFloatToInt(t * scale);
            }
        }
    }

__global__ void
d_boxfilter_rgba_y(unsigned int *id, unsigned int *od, int w, int h, int r)
    {
    unsigned int x = blockIdx.x*blockDim.x + threadIdx.x;
    id = &id[x];
    od = &od[x];

    float scale = 1.0f / (float)((r << 1) + 1);

    float4 t;
    // partea din stanga
    t = rgbaIntToFloat(id[0]) * r;

    for (int y = 0; y < (r + 1); y++)
        {
        t += rgbaIntToFloat(id[y*w]);
        }

    od[0] = rgbaFloatToInt(t * scale);

    for (int y = 1; y < (r + 1); y++)
        {
        t += rgbaIntToFloat(id[(y + r) * w]);
        t -= rgbaIntToFloat(id[0]);
        od[y * w] = rgbaFloatToInt(t * scale);
        }

    // main loop
    for (int y = (r + 1); y < (h - r); y++)
        {
        t += rgbaIntToFloat(id[(y + r) * w]);
        t -= rgbaIntToFloat(id[((y - r) * w) - w]);
        od[y * w] = rgbaFloatToInt(t * scale);
        }

    // right side
    for (int y = h - r; y < h; y++)
        {
        t += rgbaIntToFloat(id[(h - 1) * w]);
        t -= rgbaIntToFloat(id[((y - r) * w) - w]);
        od[y * w] = rgbaFloatToInt(t * scale);
        }
    }
</code>```

This should be a box filter with CUDA.
From what I have read this should make an average with a given radius.
But in d_boxfilter_rgba_y make something like this:

```<code>od[0] = rgbaFloatToInt(t * scale);
</code>```

I don't understand why is used this scale and why are made all that loops when there should be just one. To calculate the value from -r to +r and divide this by a number of pixels.

Can somebody help me?

答:
To calculate the average of a box with radius 1 (3 values), you do:

```<code>(box[0] + box[1] + box[2]) / 3 // which is equal to
(box[0] + box[1] + box[2] * 1/3 // which is equal to your scale factor
</code>```

The calculation of scale is:

```<code>1.0f / (float)((r << 1) + 1); // equal to
1 / ((r * 2) + 1) // equal to
1 / (2r + 1) // 2r because you go to the left and right and +1 for the middle
</code>```

The two for loops are used, because the "sliding window" optimisation is used. First the first box is calculated:

```<code>for (int x = -r; x <= r; x++)
{
    t += tex2D(rgbaTex, x, y);
}
</code>```

And then for each step to the right, the value right of the box is added and the most left value of the box is removed. That way you can calculate the sum of the box with just 2 operations instead of 2*r + 1 operations.

```<code>for (int x = 1; x < w; x++)
{
    t += tex2D(rgbaTex, x + r, y);
    t -= tex2D(rgbaTex, x - r - 1, y);
    od[y * w + x] = rgbaFloatToInt(t * scale);
    }
}
</code>```

Title: How CUDA box filter works?

Body:
I have this sample of code that I try to understand it:

    __global__ void
d_boxfilter_rgba_x(unsigned int *od, int w, int h, int r)
    {
    float scale = 1.0f / (float)((r << 1) + 1);
    unsigned int y = blockIdx.x*blockDim.x + threadIdx.x;

    if (y < h)
        {
        float4 t = make_float4(0.0f);

        for (int x = -r; x <= r; x++)
            {
            t += tex2D(rgbaTex, x, y);
            }

        od[y * w] = rgbaFloatToInt(t * scale);

        for (int x = 1; x < w; x++)
            {
            t += tex2D(rgbaTex, x + r, y);
            t -= tex2D(rgbaTex, x - r - 1, y);
            od[y * w + x] = rgbaFloatToInt(t * scale);
            }
        }
    }

__global__ void
d_boxfilter_rgba_y(unsigned int *id, unsigned int *od, int w, int h, int r)
    {
    unsigned int x = blockIdx.x*blockDim.x + threadIdx.x;
    id = &id[x];
    od = &od[x];

    float scale = 1.0f / (float)((r << 1) + 1);

    float4 t;
    // partea din stanga
    t = rgbaIntToFloat(id[0]) * r;

    for (int y = 0; y < (r + 1); y++)
        {
        t += rgbaIntToFloat(id[y*w]);
        }

    od[0] = rgbaFloatToInt(t * scale);

    for (int y = 1; y < (r + 1); y++)
        {
        t += rgbaIntToFloat(id[(y + r) * w]);
        t -= rgbaIntToFloat(id[0]);
        od[y * w] = rgbaFloatToInt(t * scale);
        }

    // main loop
    for (int y = (r + 1); y < (h - r); y++)
        {
        t += rgbaIntToFloat(id[(y + r) * w]);
        t -= rgbaIntToFloat(id[((y - r) * w) - w]);
        od[y * w] = rgbaFloatToInt(t * scale);
        }

    // right side
    for (int y = h - r; y < h; y++)
        {
        t += rgbaIntToFloat(id[(h - 1) * w]);
        t -= rgbaIntToFloat(id[((y - r) * w) - w]);
        od[y * w] = rgbaFloatToInt(t * scale);
        }
    }

This should be a box filter with CUDA.
From what I have read this should make an average with a given radius.
But in d_boxfilter_rgba_y make something like this:

od[0] = rgbaFloatToInt(t * scale);

I don't understand why is used this scale and why are made all that loops when there should be just one. To calculate the value from -r to +r and divide this by a number of pixels.

Can somebody help me?

Body:
To calculate the average of a box with radius 1 (3 values), you do:

(box[0] + box[1] + box[2]) / 3 // which is equal to
(box[0] + box[1] + box[2] * 1/3 // which is equal to your scale factor

The calculation of scale is:

1.0f / (float)((r << 1) + 1); // equal to
1 / ((r * 2) + 1) // equal to
1 / (2r + 1) // 2r because you go to the left and right and +1 for the middle

The two for loops are used, because the "sliding window" optimisation is used. First the first box is calculated:

for (int x = -r; x <= r; x++)
{
    t += tex2D(rgbaTex, x, y);
}

And then for each step to the right, the value right of the box is added and the most left value of the box is removed. That way you can calculate the sum of the box with just 2 operations instead of 2*r + 1 operations.

for (int x = 1; x < w; x++)
{
    t += tex2D(rgbaTex, x + r, y);
    t -= tex2D(rgbaTex, x - r - 1, y);
    od[y * w + x] = rgbaFloatToInt(t * scale);
    }
}


问:
Spotfire: Create button to start loading data ,instead of using load data on demand
Is there any way to add a button to load data as and when required. I am aware of load data on demand option, This is not helping as I have more than 10 millions of data rows and it still takes time to load in spotfire. I need an option where in the visualization has to start the data loading when i click the button to start , where as "load data on demand" is an option to load at the source itself.

Under TEXT AREA we have an option to add "INSERT ACTION ITEM" which gives option to add button, can we use it and create an button called "Start" which will be used to load the data?

答:
Yes.

Add the button as you described in your post

Click Script > New

Add this script and name it what ever you want, replacing 'Book1' with your table name

Note, you should still leave the data table as load on demand and then just use this to refresh the data, that way the initial load doesn't happen on start up

```<code>from System.Collections.Generic import List, Dictionary
from Spotfire.Dxp.Data import DataTable
Tbls = List[DataTable]()
Tbls.Add(Document.Data.Tables['Book1'])

Document.Data.Tables.Refresh(Tbls)
</code>```

Also, if you are doing this in the web player, you can take advantage of paramertized load on demand features, or store the analysis in the web player cache and avoid this all together.

Body:
Yes.

Add the button as you described in your post

Click Script > New

Add this script and name it what ever you want, replacing 'Book1' with your table name

Note, you should still leave the data table as load on demand and then just use this to refresh the data, that way the initial load doesn't happen on start up

from System.Collections.Generic import List, Dictionary
from Spotfire.Dxp.Data import DataTable
Tbls = List[DataTable]()
Tbls.Add(Document.Data.Tables['Book1'])

Document.Data.Tables.Refresh(Tbls)

Also, if you are doing this in the web player, you can take advantage of paramertized load on demand features, or store the analysis in the web player cache and avoid this all together.


问:
object oriented php code Error
```<code>// connection.php file

<?php

class Connection{

   private $host;
   private $username;
   private $password;
   private $database;

   public function __construct($host,$username,$password,$database)
   {
     try{
     $conn = new PDO("mysql:host=".$host.";dbname=".$database, $username, $password);
     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     return $conn;
     }catch(PDOException $e)
     {
        return $e->getMessage();
     }
   }

}

?>

// user.php

<?php

class Users extends Connection{

  private $username;
  private $email;
  private $password;

  public function __construct($username,$email,$password){

    $this->username=$username;
    $this->email=$email;
    $this->password=$password;

  }

  public function addUser(){
    $conn = new Connection("localhost","root","","userdata");
    echo "database connection established";
    die();
    $sql = $conn->prepare("INSERT INTO information (UserName, Email, Password) VALUES (?, ?, ?)");
    $conn->bind_param("sss", $username, $email, $password);
    $username=this->username;
    $password=this->password;
    $email=this->email;
    $sql->execute();

    echo "New records created successfully";

    $sql->close();
    $conn->close();

  }
}

?>

process.php

<?php

include('lib/connection.php');

if(isset($_POST['username']) && isset($_POST['email']) && isset($_POST['password']))
{
  $user = new User("Gautam","gautam@mail.com","123456");
  $user->addUser();
}

?>
</code>```

So the Problem when i try to execute the process.php file the records are not added to the database.So i have created connection class separately where i have written the logic for database connection then i inherited that class to the users where i added the users to the database then i called the object of user class in process.php but records are not added to the database.Please clarify what is the problem associated with it.

答:
The problem with your code is that you did not bind any parameters before executing.

check these lines :

```<code>$sql = $conn->prepare()
$conn->bind_param("sss", $username, $email, $password);
</code>```

this line should be $sql->bind_param("sss", $username, $email, $password);

and also note that PDO does not have bind_param() function it have : bindParam()

therefore you need

```<code>    $sql->bindParam(1, $this->username);
    $sql->bindParam(2, $this->email);
    $sql->bindParam(3, $this->password);
</code>```

This code below should work :

```<code><?php

class Users extends Connection
{

    private $username;
    private $email;
    private $password;

    public function __construct($username, $email, $password)
    {
        $this->username = $username;
        $this->email    = $email;
        $this->password = $password;

    }

    public function addUser()
    {
        $conn = new Connection("localhost", "root", "", "userdata");
        echo "database connection established";

        $username = $this->username;
        $password = $this->password;
        $email    = $this->email;

        $sql = $conn->prepare("INSERT INTO information (UserName, Email, Password) VALUES (?, ?, ?)")->execute(array($username,$email,$password));

        if (!$sql) {

            print_r("error : " . $conn->errorInfo());
        } else {

            echo "New records created successfully";
        }
        $sql->close();
        $conn->close();
    }
}

?>
</code>```

PS: Don't store passwords in plain text, use php builtin function such
  as password_hash() and password_verify() to prepare your password.

Title: object oriented php code Error

Body:
// connection.php file

<?php

class Connection{

   private $host;
   private $username;
   private $password;
   private $database;

   public function __construct($host,$username,$password,$database)
   {
     try{
     $conn = new PDO("mysql:host=".$host.";dbname=".$database, $username, $password);
     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     return $conn;
     }catch(PDOException $e)
     {
        return $e->getMessage();
     }
   }

}

?>

// user.php

<?php

class Users extends Connection{

  private $username;
  private $email;
  private $password;

  public function __construct($username,$email,$password){

    $this->username=$username;
    $this->email=$email;
    $this->password=$password;

  }

  public function addUser(){
    $conn = new Connection("localhost","root","","userdata");
    echo "database connection established";
    die();
    $sql = $conn->prepare("INSERT INTO information (UserName, Email, Password) VALUES (?, ?, ?)");
    $conn->bind_param("sss", $username, $email, $password);
    $username=this->username;
    $password=this->password;
    $email=this->email;
    $sql->execute();

    echo "New records created successfully";

    $sql->close();
    $conn->close();

  }
}

?>

process.php

<?php

include('lib/connection.php');

if(isset($_POST['username']) && isset($_POST['email']) && isset($_POST['password']))
{
  $user = new User("Gautam","gautam@mail.com","123456");
  $user->addUser();
}

?>

So the Problem when i try to execute the process.php file the records are not added to the database.So i have created connection class separately where i have written the logic for database connection then i inherited that class to the users where i added the users to the database then i called the object of user class in process.php but records are not added to the database.Please clarify what is the problem associated with it.

Body:
The problem with your code is that you did not bind any parameters before executing.

check these lines :

$sql = $conn->prepare()
$conn->bind_param("sss", $username, $email, $password);

this line should be $sql->bind_param("sss", $username, $email, $password);

and also note that PDO does not have bind_param() function it have : bindParam()

therefore you need

    $sql->bindParam(1, $this->username);
    $sql->bindParam(2, $this->email);
    $sql->bindParam(3, $this->password);

This code below should work :

<?php

class Users extends Connection
{

    private $username;
    private $email;
    private $password;

    public function __construct($username, $email, $password)
    {
        $this->username = $username;
        $this->email    = $email;
        $this->password = $password;

    }

    public function addUser()
    {
        $conn = new Connection("localhost", "root", "", "userdata");
        echo "database connection established";

        $username = $this->username;
        $password = $this->password;
        $email    = $this->email;

        $sql = $conn->prepare("INSERT INTO information (UserName, Email, Password) VALUES (?, ?, ?)")->execute(array($username,$email,$password));

        if (!$sql) {

            print_r("error : " . $conn->errorInfo());
        } else {

            echo "New records created successfully";
        }
        $sql->close();
        $conn->close();
    }
}

?>

PS: Don't store passwords in plain text, use php builtin function such
  as password_hash() and password_verify() to prepare your password.


问:
Getting rows count as zero after slecting data from where = date as using distinct above
Hi am retreiving the distinct dates then am trying to retreive the rows with that dates but am getting them as zero..
Here is code

```<code>$sql = "SELECT DISTINCT  date FROM video_data ORDER BY id DESC";
$result = mysqli_query($connection, $sql);
while ($row = mysqli_fetch_assoc($result)) {
   $date = $row['date'];
  echo "<tr>";
     echo "<td>$date</td>";
         $query_order = "SELECT * FROM video_data WHERE date=$date";
         $query_order_total = mysqli_query($connection,$query_order);
         var_dump($query_order);
         $total =  mysqli_num_rows($query_order_total);
     echo "<td>$total</td>";
  echo"<tr>";
</code>```

But when am selecting "SELECT * FROM video_data" its showing correct count

答:
you are missing ' ' around $date

$query_order = "SELECT * FROM video_data WHERE date='$date'";

That said: when you have, let's say, 60 dates found in your first query, you will than fire 60 new queries to find the actual data.

how about:

```<code>$sql = "SELECT COUNT(*) total, date
        FROM video_data
        GROUP BY date
        ORDER BY date DESC";
$result = mysqli_query($connection, $sql);
while ($row = mysqli_fetch_assoc($result)) {
  echo "<tr>";
  echo "<td>". $row['date'] ."</td>";
  echo "<td>". $row['total']. "</td>";
  echo"<tr>";
}
</code>```

Body:
Hi am retreiving the distinct dates then am trying to retreive the rows with that dates but am getting them as zero..
Here is code

$sql = "SELECT DISTINCT  date FROM video_data ORDER BY id DESC";
$result = mysqli_query($connection, $sql);
while ($row = mysqli_fetch_assoc($result)) {
   $date = $row['date'];
  echo "
";
     echo "$date	";
         $query_order = "SELECT * FROM video_data WHERE date=$date";
         $query_order_total = mysqli_query($connection,$query_order);
         var_dump($query_order);
         $total =  mysqli_num_rows($query_order_total);
     echo "$total	";
  echo"
";

But when am selecting "SELECT * FROM video_data" its showing correct count

Body:
you are missing ' ' around $date

$query_order = "SELECT * FROM video_data WHERE date='$date'";

That said: when you have, let's say, 60 dates found in your first query, you will than fire 60 new queries to find the actual data.

how about:

$sql = "SELECT COUNT(*) total, date
        FROM video_data
        GROUP BY date
        ORDER BY date DESC";
$result = mysqli_query($connection, $sql);
while ($row = mysqli_fetch_assoc($result)) {
  echo "<tr>";
  echo "<td>". $row['date'] ."</td>";
  echo "<td>". $row['total']. "</td>";
  echo"<tr>";
}


问:
Cloudera Cluster Deployment bootstrap failed error on EC2 using Director
I have successfully deployed Cloudera Director and Cloudera Manager on EC2. I can access both director and manager instances from browser and can do ssh to those instances. Cloudera Manager server and agent is running fine and checked it by running following commands.

Next step is - I want to deploy cluster. However its failing and I am getting Bootstrap failed error. I checked application.log file on director and found exception as - Caused by:

java.net.ConnectException: ConnectException invoking http://:7180/api/v6/commands/158: Connection refused (Connection refused)

After checking services status, I found that during deployment of cluster, somehow cloudera-scm-manager service is getting stopped (cloudera-scm-server). However, before deployment of cluster, I had verified that cloudera-scm-server service was up and running.

I tried deploying cluster number of times and using both t2 small and m4 large instance types. I am getting same exception.

After getting error, if I restart cloudera-scm-service, it starts, and works fine. But during cluster deployment it gets stops automatically which I guess fails the cluster deployment. Not sure how and why?

Any idea what could be the issue? Can someone provide any pointers/help to resolve this issue?

Version details used for deployment as follows -

Cloudera Director version - 2.4.1

Cloudera Manager version - 5.11.1

EC2 instance - tried with both t2 small and m4 large instance type.

EC2 instance OS - RHEL 6.7, 64-bit

Cluster config selected - 1 master,1 worker,1 gateway

Cluster services selected - Core Hadoop with Spark on YARN (this includes following services - HDFS, Hive, Hue, Oozie, Spark on YARN, YARN, ZooKeeper)

Any help/input/pointers to solve this issue, greatly appreciated.

Thanks so much in advance.

-picku

答:
Picku

My first guess based on your symptoms is that your CM instance is too small. Linux has an OOM Killer that will terminate arbitrary processes if there is not enough memory for the OS to run. This is likely the reason that you don't see the cloudera-scm-service as running. I believe you can look in /var/log/messages to find the "smoking gun" that implicates the OOM Killer.

Please refer to the Cloudera Enterprise Reference Architecture for AWS Deployments for recommendations on instance types.
http://www.cloudera.com/documentation/other/reference-architecture/PDF/cloudera_ref_arch_aws.pdf

Good Luck!
David


问:
Automatic update of entity every day
I'm creating my portfolio with Symfony 3 and I want to show my skills with my experience.

I have a "Skill" entity with a "startAt" param (type=datetime) and a "exp" param (string).

The "exp" param = the difference between "startAt" and the current date.

I add some lifecycle callback so the "exp" param update every time I touch my "Skill" entity but here is my question:

How can I update my entity every day without touching it?

For exemple right now I have "exp = 6 months" but next month this param need to be "7 months".

答:
Since "startAt" is likely mapped to a field name in the database called "start_at", this date is all the data you need to set and store.  The method in the entity called getExp(), which maps to the variable "exp" would then take $this->startAt() value and calculate the difference between that start at time and the current time.  You can use the PHP DateTime object to calculate the difference in units of days, months or years, depending on your preference.

Also, "exp" doesn't need to be a field you need to store or map to the database because it can easily be calculated on the fly based on the "startAt" date value anyway.

Title: Automatic update of entity every day


问:
Java: Convert byte to integer
I need to convert 2 byte array ( byte[2] ) to integer value in java.  How can I do that?</p>

答:
You can use ByteBuffer for this:

```<code>ByteBuffer buffer = ByteBuffer.wrap(myArray);
buffer.order(ByteOrder.LITTLE_ENDIAN);  // if you want little-endian
int result = buffer.getShort();
</code>```

See also Convert 4 bytes to int.

ContentLicense: CC BY-SA 2.5

Title: Java: Convert byte to integer

Body:
You can use ByteBuffer for this:

ByteBuffer buffer = ByteBuffer.wrap(myArray);
buffer.order(ByteOrder.LITTLE_ENDIAN);  // if you want little-endian
int result = buffer.getShort();

See also Convert 4 bytes to int.


问:
Angular 2:Google Maps and Angular Google Places
I´m using two components  in the same page,https://angular-maps.com and angular2-google-map-auto-complete. https://www.npmjs.com/package/angular2-google-map-auto-complete. I define the angular maps key on this way:

```<code>AgmCoreModule.forRoot({
 apiKey: 'API_KEY'
})
</code>```

And for google map automplete on index file:

```<code><script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places"></script>
</code>```

The problem is when I use that components on the same page throws error

```<code>You have included the Google Maps API multiple times on this page. This may cause unexpected errors.
</code>```

I know what is the problem but, hoy define single API_KEY to avoid  errors

答:
just remove the

```<code><script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places"></script>
</code>```

from your index.html and add your api key inside the amgCoreModule declaration.

Body:
I´m using two components  in the same page,https://angular-maps.com and angular2-google-map-auto-complete. https://www.npmjs.com/package/angular2-google-map-auto-complete. I define the angular maps key on this way:

AgmCoreModule.forRoot({
 apiKey: 'API_KEY'
})

And for google map automplete on index file:

The problem is when I use that components on the same page throws error

You have included the Google Maps API multiple times on this page. This may cause unexpected errors.

I know what is the problem but, hoy define single API_KEY to avoid  errors

Body:
just remove the

<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places"></script>

from your index.html and add your api key inside the amgCoreModule declaration.


问:
Creating a link through button
Anybody please explain how to create a button which redirects to a link/website by clicking on it.
Please provide a code as example.</p>

答:
try this</p>

```<code> <button onclick="window.location='http://google.com'">redirect me</button>
</code>```

Title: Creating a link through button

Body:
try this

 <button onclick="window.location='http://google.com'">redirect me</button>


问:
SQL Server is reading only first row from valid JSON
My JSON is like below. This JSON is read by ADF without problem and imports all rows.

```<code>{"Row":{"Col1":"Val1", "Col2":"Val2"}}
{"Row":{"Col1":"Val1", "Col2":"Val2"}}
{"Row":{"Col1":"Val1", "Col2":"Val2"}}
</code>```

However when I read this from SQL using below query, it returns only first record.

```<code>SELECT * FROM OPENJSON(@JSONDATA, '$')
with (
    Col1 varchar(25) '$.Row.Col1'
);
</code>```

Do you know why?

答:
I think you have to change your JSON data structure like below. Yours is also not valid JSON. Try any online JSON validators to see the difference.

Correct one would be:

```<code>[
  {"Col1":"Val1", "Col2":"Val2"},
  {"Col1":"Val1", "Col2":"Val2"},
  {"Col1":"Val1", "Col2":"Val2"}
]
</code>```

As yours is simply an object it will probably get just one row.  MSDN uses OPENJSON like this too.

After you changed it to an array you have to edit your query like this:

```<code>SELECT * FROM OPENJSON(@JSONDATA, '$')
with (
    Col1 varchar(25) '$.Col1',
    Col2 varchar(25) '$.Col2'
);
</code>```

It gets all of the rows now as in the screenshot.

Body:
My JSON is like below. This JSON is read by ADF without problem and imports all rows.

{"Row":{"Col1":"Val1", "Col2":"Val2"}}
{"Row":{"Col1":"Val1", "Col2":"Val2"}}
{"Row":{"Col1":"Val1", "Col2":"Val2"}}

However when I read this from SQL using below query, it returns only first record.

SELECT * FROM OPENJSON(@JSONDATA, '$')
with (
    Col1 varchar(25) '$.Row.Col1'
);

Do you know why?

Body:
I think you have to change your JSON data structure like below. Yours is also not valid JSON. Try any online JSON validators to see the difference.

Correct one would be:

[
  {"Col1":"Val1", "Col2":"Val2"},
  {"Col1":"Val1", "Col2":"Val2"},
  {"Col1":"Val1", "Col2":"Val2"}
]

As yours is simply an object it will probably get just one row.  MSDN uses OPENJSON like this too.

After you changed it to an array you have to edit your query like this:

SELECT * FROM OPENJSON(@JSONDATA, '$')
with (
    Col1 varchar(25) '$.Col1',
    Col2 varchar(25) '$.Col2'
);

It gets all of the rows now as in the screenshot.


问:
Using cat and execvp
Trying to understand why this section of code using the cat command isn't working with execvp in C.

```<code>char *in[5] ={"cat", "file1.txt", ">>", "file2.txt", 0};
execvp(in[0], in);
</code>```

When I run it displays the contents of file1.txt but then says:

cat: >> No such file or directory.

Then displays the contents of file2.txt
Why wouldn't it recognize the >> operator in this instance?

答:
You can read the "man tee" command which it  read from standard input and write to standard output and files. You could achieve this with below example.</p>

```<code>#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

/*
Implementation of below command:
cat file1.txt > file2.txt
*/

char *cmd1[] = { "/bin/cat", "file1.txt", 0 };
char *cmd2[] = { "tee", "file2.txt", 0 };

static void sigchld_hdl (int sig)
{
    int status;
    while (waitpid(-1, &status, 0) > 0) {
        if(WIFEXITED(status))
            printf("Child exited with code %d\n", WEXITSTATUS(status)); }
}

int runcmd(int pfd[])
{
    int i=0;

    switch (fork()) {
        case -1:
            perror ("fork");
            return 1;
        case 0:
            dup2(pfd[0], 0);
            close(pfd[1]);  /* the child does not need this end of the pipe */
            execvp(cmd2[0], cmd2);
            perror(cmd2[0]);
            exit(10);
        default: /* parent */
            dup2(pfd[1], 1);
            close(pfd[0]);  /* the parent does not need this end of the pipe */
            execvp(cmd1[0], cmd1);
            perror(cmd1[0]);

    }
    sleep(1);
}

int main (int argc, char *argv[])
{
    struct sigaction act;
    int fd[2];

    pipe(fd);

    memset (&act, 0, sizeof(act));
    act.sa_handler = sigchld_hdl;

    if (sigaction(SIGCHLD, &act, 0)) {
        perror ("sigaction");
        return 1;
    }
    runcmd(fd);

    return 0;
}
</code>```

Title: Using cat and execvp

Body:
Trying to understand why this section of code using the cat command isn't working with execvp in C.

char *in[5] ={"cat", "file1.txt", ">>", "file2.txt", 0};
execvp(in[0], in);

When I run it displays the contents of file1.txt but then says:

cat: >> No such file or directory.

Then displays the contents of file2.txt
Why wouldn't it recognize the >> operator in this instance?

Body:
You can read the "man tee" command which it  read from standard input and write to standard output and files. You could achieve this with below example.

#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

/*
Implementation of below command:
cat file1.txt > file2.txt
*/

char *cmd1[] = { "/bin/cat", "file1.txt", 0 };
char *cmd2[] = { "tee", "file2.txt", 0 };

static void sigchld_hdl (int sig)
{
    int status;
    while (waitpid(-1, &status, 0) > 0) {
        if(WIFEXITED(status))
            printf("Child exited with code %d\n", WEXITSTATUS(status)); }
}

int runcmd(int pfd[])
{
    int i=0;

    switch (fork()) {
        case -1:
            perror ("fork");
            return 1;
        case 0:
            dup2(pfd[0], 0);
            close(pfd[1]);  /* the child does not need this end of the pipe */
            execvp(cmd2[0], cmd2);
            perror(cmd2[0]);
            exit(10);
        default: /* parent */
            dup2(pfd[1], 1);
            close(pfd[0]);  /* the parent does not need this end of the pipe */
            execvp(cmd1[0], cmd1);
            perror(cmd1[0]);

    }
    sleep(1);
}

int main (int argc, char *argv[])
{
    struct sigaction act;
    int fd[2];

    pipe(fd);

    memset (&act, 0, sizeof(act));
    act.sa_handler = sigchld_hdl;

    if (sigaction(SIGCHLD, &act, 0)) {
        perror ("sigaction");
        return 1;
    }
    runcmd(fd);

    return 0;
}


问:
How would you represent a hashtable collection in a database schema?
If you were trying to create a domain object in a database schema, and in your code said domain object has a hashtable/list member, like so:

```<code>public class SpaceQuadrant : PersistentObject
{

    public SpaceQuadrant()
    {
    }

    public virtual Dictionary<SpaceCoordinate, SpaceObject> Space
    {
        get;
        set;
    }
}
</code>```

A Dictionary is just a hashtable/list mapping object keys to value keys, I've come up with multiple ways to do this, creating various join tables or loading techniques, but they all kind of suck in terms of getting that O(1) access time that you get in a hashtable.

How would you represent the SpaceQuadrant, SpaceCoordinate, and Space Object in a database schema?
A simple schema code description would be nice,
ie.

```<code>table SpaceQuadrant
{
    ID int not null primary key,
    EntryName varchar(255) not null,
    SpaceQuadrantJoinTableId int not null
                 foreign key references ...anothertable...
}
</code>```

but any thoughts at all would be nice as well, thanks for reading!

More Information:

Thanks for the great answers, already, I've only skimmed them, and I want to take some time thinking about each before I respond.

If you think there is a better way to define these classes, then by all means show me an example, any language your comfortable with is cool

答:
Relations are not hash tables; they are sets.

I wouldn't organize the database using the coordinates as the key.  What if an object changes location?  Instead, I would probably treat coordinates as attributes of an object.

Also, I assume there is a fixed number of dimensions, for example, three.  If so, then you can store these attributes of an object in fixed columns:

```<code>CREATE TABLE SpaceQuadrant (
  quadrant_id INT NOT NULL PRIMARY KEY,
  quadrant_name VARCHAR(20)
  -- other attributes
);

CREATE TABLE SpaceObject (
  object_id INT NOT NULL PRIMARY KEY,
  x NUMERIC(9,2) NOT NULL,
  y NUMERIC(9,2) NOT NULL
  z NUMERIC(9,2) NOT NULL,
  object_name VARCHAR(20) NOT NULL,
  -- other attributes
  quadrant_id INT NOT NULL,
  FOREIGN KEY (quadrant_id) REFERENCES SpaceQuadrant(quadrant_id)
);
</code>```

In your object-oriented class, it's not clear why your objects are in a dictionary.  You mention accessing them in O(1) time, but why do you do that by coordinate?

If you're using that to optimize finding objects that are near a certain point (the player's spaceship, for instance), you could also build into your SQL query that populates this SpaceQuadrant a calculation of every object's distance from that given point, and sort the results by distance.

I don't know enough about your program to know if these suggestions are relevant.  But are they at least making you think of different ways of organizing the data?

Body:
If you were trying to create a domain object in a database schema, and in your code said domain object has a hashtable/list member, like so:

public class SpaceQuadrant : PersistentObject
{

    public SpaceQuadrant()
    {
    }

    public virtual Dictionary<SpaceCoordinate, SpaceObject> Space
    {
        get;
        set;
    }
}

A Dictionary is just a hashtable/list mapping object keys to value keys, I've come up with multiple ways to do this, creating various join tables or loading techniques, but they all kind of suck in terms of getting that O(1) access time that you get in a hashtable.

How would you represent the SpaceQuadrant, SpaceCoordinate, and Space Object in a database schema?
A simple schema code description would be nice,
ie.

table SpaceQuadrant
{
    ID int not null primary key,
    EntryName varchar(255) not null,
    SpaceQuadrantJoinTableId int not null
                 foreign key references ...anothertable...
}

but any thoughts at all would be nice as well, thanks for reading!

More Information:

Thanks for the great answers, already, I've only skimmed them, and I want to take some time thinking about each before I respond.

If you think there is a better way to define these classes, then by all means show me an example, any language your comfortable with is cool

Body:
Relations are not hash tables; they are sets.

I wouldn't organize the database using the coordinates as the key.  What if an object changes location?  Instead, I would probably treat coordinates as attributes of an object.

Also, I assume there is a fixed number of dimensions, for example, three.  If so, then you can store these attributes of an object in fixed columns:

CREATE TABLE SpaceQuadrant (
  quadrant_id INT NOT NULL PRIMARY KEY,
  quadrant_name VARCHAR(20)
  -- other attributes
);

CREATE TABLE SpaceObject (
  object_id INT NOT NULL PRIMARY KEY,
  x NUMERIC(9,2) NOT NULL,
  y NUMERIC(9,2) NOT NULL
  z NUMERIC(9,2) NOT NULL,
  object_name VARCHAR(20) NOT NULL,
  -- other attributes
  quadrant_id INT NOT NULL,
  FOREIGN KEY (quadrant_id) REFERENCES SpaceQuadrant(quadrant_id)
);

In your object-oriented class, it's not clear why your objects are in a dictionary.  You mention accessing them in O(1) time, but why do you do that by coordinate?

If you're using that to optimize finding objects that are near a certain point (the player's spaceship, for instance), you could also build into your SQL query that populates this SpaceQuadrant a calculation of every object's distance from that given point, and sort the results by distance.

I don't know enough about your program to know if these suggestions are relevant.  But are they at least making you think of different ways of organizing the data?

OwnerDisplayName: Bill Karwin


答:
This can be done using Javascript. The button code will be as follows:</p>

```<code><button onclick="redirect()">Take me to google</button>

<script>
function redirect() {
    window.location = "http://google.com";
}
</script>
</code>```

Title: Creating a link through button

Body:
Anybody please explain how to create a button which redirects to a link/website by clicking on it.
Please provide a code as example.

Body:
This can be done using Javascript. The button code will be as follows:

<button onclick="redirect()">Take me to google</button>

<script>
function redirect() {
    window.location = "http://google.com";
}
</script>


问:
Retrieving latest version of artifact with custom repository layout
My intent is to store SNAPSHOT and RELEASE firmware binary images in Artifactory.

I have setup a custom repository layout where the artifact path pattern is set to -

```<code>[org]/[module]/[baseRev]-[folderItegRev]/[baseRev]-[folderItegRev](-[fileItegRev]).[ext]
</code>```

Here are screenshots of the configuration -

I created a new repository based on the generic package type and chose the custom repository layout that I created.

I have uploaded release and snapshot artifacts to this repo and this is what it looks like on the web UI -

```<code>myrepo
    mygroup/myartifactid
        1.0.0-RELEASE
            1.0.0-RELEASE.bin
        2.0.0-RELEASE
            2.0.0-RELEASE.bin
        3.0.0-SNAPSHOT
            3.0.0-SNAPSHOT-20170630161531.bin
            3.0.0-SNAPSHOT-20171202161531.bin
            3.0.0-SNAPSHOT-20171231161531.bin
</code>```

Now if I use the REST API to search for the latest artifact based on layout as per the API published here

```<code>GET http://artifactory-server:8082/artifactory/api/search/latestVersion?g=mygroup&a=myartifactid&v=3.0.0-SNAPSHOT
</code>```

I get the below response -

```<code>{
  "errors": [
    {
      "status": 404,
      "message": "Unable to find artifact versions"
    }
  ]
}
</code>```

What am I doing wrong? I want to be able to search for the latest release and snapshot versions using the REST API.

答:
Make sure that "Folder Integration Revision RegExp" and "File Integration Revision RegExp" are defined for your custom layout.

In the case of your layout, they should be:

Folder Integration Revision RegExp: SNAPSHOT

File Integration Revision RegExp:(?:[0-9]{14})

To make sure the layout is properly configured, test it against a sample path, for example: mygroup/myartifactid/3.0.0-SNAPSHOT/3.0.0-SNAPSHOT-20170630161531.bin

If everything is configured correctly the test result should show the various parts of the layout: organization, module etc.

In addition, it is better, in terms of performance, to specify which repositories you wish to query, for example:

```<code>GET http://localhost:8081/artifactory/api/search/latestVersion?g=mygroup&a=myartifactid&v=3.0.0-SNAPSHOT&repos=myrepo
</code>```

Body:
My intent is to store SNAPSHOT and RELEASE firmware binary images in Artifactory.

I have setup a custom repository layout where the artifact path pattern is set to -

[org]/[module]/[baseRev]-[folderItegRev]/[baseRev]-[folderItegRev](-[fileItegRev]).[ext]

Here are screenshots of the configuration -

I created a new repository based on the generic package type and chose the custom repository layout that I created.

I have uploaded release and snapshot artifacts to this repo and this is what it looks like on the web UI -

myrepo
    mygroup/myartifactid
        1.0.0-RELEASE
            1.0.0-RELEASE.bin
        2.0.0-RELEASE
            2.0.0-RELEASE.bin
        3.0.0-SNAPSHOT
            3.0.0-SNAPSHOT-20170630161531.bin
            3.0.0-SNAPSHOT-20171202161531.bin
            3.0.0-SNAPSHOT-20171231161531.bin

Now if I use the REST API to search for the latest artifact based on layout as per the API published here

GET http://artifactory-server:8082/artifactory/api/search/latestVersion?g=mygroup&a=myartifactid&v=3.0.0-SNAPSHOT

I get the below response -

{
  "errors": [
    {
      "status": 404,
      "message": "Unable to find artifact versions"
    }
  ]
}

What am I doing wrong? I want to be able to search for the latest release and snapshot versions using the REST API.

Body:
Make sure that "Folder Integration Revision RegExp" and "File Integration Revision RegExp" are defined for your custom layout.

In the case of your layout, they should be:

Folder Integration Revision RegExp: SNAPSHOT

File Integration Revision RegExp:(?:[0-9]{14})

To make sure the layout is properly configured, test it against a sample path, for example: mygroup/myartifactid/3.0.0-SNAPSHOT/3.0.0-SNAPSHOT-20170630161531.bin

If everything is configured correctly the test result should show the various parts of the layout: organization, module etc.

In addition, it is better, in terms of performance, to specify which repositories you wish to query, for example:

GET http://localhost:8081/artifactory/api/search/latestVersion?g=mygroup&a=myartifactid&v=3.0.0-SNAPSHOT&repos=myrepo


问:
Symfony 2.8 Can't create relations between two tables
I have a problem with creating relations between two tables in Symfony (Doctrine).
I'm creating addressbook where I have Person Entity and I want to have relation wit Address Entity with relations OneToMany(One Person has many addresses).
When I run:

```<code>php app/console doctrine:generate:entities AdressBookBundle/Entiti/Address
</code>```

I got error:

```<code>[RuntimeException]
  Namespace "AdressBookBundle\Entiti\Address" does not contain any mapped entities.
</code>```

Below I put code with both Entities:

Person:

```<code><?php

namespace AdressBookBundle\Entity;

use AdressBookBundle\Entity\Address;
use Doctrine\ORM\Mapping as ORM;

/**
 * Person
 *
 * @ORM\Table(name="person")
 * @ORM\Entity(repositoryClass="AdressBookBundle\Repository\PersonRepository")
 */
class Person
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="surname", type="string", length=255)
     */
    private $surname;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="string", length=500)
     */
    private $description;

    /**
     * @ORM\OneToMany(targetEntity="Address", mappedBy="person")
     */
    private $address;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Person
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set surname
     *
     * @param string $surname
     * @return Person
     */
    public function setSurname($surname)
    {
        $this->surname = $surname;

        return $this;
    }

    /**
     * Get surname
     *
     * @return string
     */
    public function getSurname()
    {
        return $this->surname;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return Person
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->address = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add address
     *
     * @param \AdressBookBundle\Entity\Address $address
     * @return Person
     */
    public function addAddress(\AdressBookBundle\Entity\Address $address)
    {
        $this->address[] = $address;

        return $this;
    }

    /**
     * Remove address
     *
     * @param \AdressBookBundle\Entity\Address $address
     */
    public function removeAddress(\AdressBookBundle\Entity\Address $address)
    {
        $this->address->removeElement($address);
    }

    /**
     * Get address
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getAddress()
    {
        return $this->address;
    }
}
</code>```

Address:

```<code><?php

namespace AdressBookBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use AdressBookBundle\Entity\Person;

/**
 * Address
 *
 * @ORM\Table(name="address")
 * @ORM\Entity(repositoryClass="AdressBookBundle\Repository\AddressRepository")
 */
class Address
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="city", type="text")
     */
    private $city;

    /**
     * @var string
     *
     * @ORM\Column(name="street", type="text")
     */
    private $street;

    /**
     * @var int
     *
     * @ORM\Column(name="house_number", type="integer")
     */
    private $houseNumber;

    /**
     * @var int
     *
     * @ORM\Column(name="house_unit_number", type="integer")
     */
    private $houseUnitNumber;

    /**
     * $@ORM\ManyToOne(targetEntity="Person", inversedBy="address")
     * @ORM\JoinColumn(name="person_id", referencedColumnName="id")
     */
    private $person;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set city
     *
     * @param string $city
     * @return Address
     */
    public function setCity($city)
    {
        $this->city = $city;

        return $this;
    }

    /**
     * Get city
     *
     * @return string
     */
    public function getCity()
    {
        return $this->city;
    }

    /**
     * Set street
     *
     * @param string $street
     * @return Address
     */
    public function setStreet($street)
    {
        $this->street = $street;

        return $this;
    }

    /**
     * Get street
     *
     * @return string
     */
    public function getStreet()
    {
        return $this->street;
    }

    /**
     * Set houseNumber
     *
     * @param integer $houseNumber
     * @return Address
     */
    public function setHouseNumber($houseNumber)
    {
        $this->houseNumber = $houseNumber;

        return $this;
    }

    /**
     * Get houseNumber
     *
     * @return integer
     */
    public function getHouseNumber()
    {
        return $this->houseNumber;
    }

    /**
     * Set houseUnitNumber
     *
     * @param integer $houseUnitNumber
     * @return Address
     */
    public function setHouseUnitNumber($houseUnitNumber)
    {
        $this->houseUnitNumber = $houseUnitNumber;

        return $this;
    }

    /**
     * Get houseUnitNumber
     *
     * @return integer
     */
    public function getHouseUnitNumber()
    {
        return $this->houseUnitNumber;
    }
}
</code>```

Could You please explain me how it excactly works?
As I understand I create relation by:

```<code>/**
     * $@ORM\ManyToOne(targetEntity="Person", inversedBy="address")
     * @ORM\JoinColumn(name="person_id", referencedColumnName="id")
*/
</code>```

And than neew column person_id is creating in Address table. Am I right?

答:
remove the "$" from @ORM\ManyToOne(targetEntity="Client").

@ORM\ManyToOne(targetEntity="Client"). remove the "$"

Body:
I have a problem with creating relations between two tables in Symfony (Doctrine).
I'm creating addressbook where I have Person Entity and I want to have relation wit Address Entity with relations OneToMany(One Person has many addresses).
When I run:

php app/console doctrine:generate:entities AdressBookBundle/Entiti/Address

I got error:

[RuntimeException]
  Namespace "AdressBookBundle\Entiti\Address" does not contain any mapped entities.

Below I put code with both Entities:

Person:

<?php

namespace AdressBookBundle\Entity;

use AdressBookBundle\Entity\Address;
use Doctrine\ORM\Mapping as ORM;

/**
 * Person
 *
 * @ORM\Table(name="person")
 * @ORM\Entity(repositoryClass="AdressBookBundle\Repository\PersonRepository")
 */
class Person
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="surname", type="string", length=255)
     */
    private $surname;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="string", length=500)
     */
    private $description;

    /**
     * @ORM\OneToMany(targetEntity="Address", mappedBy="person")
     */
    private $address;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Person
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set surname
     *
     * @param string $surname
     * @return Person
     */
    public function setSurname($surname)
    {
        $this->surname = $surname;

        return $this;
    }

    /**
     * Get surname
     *
     * @return string
     */
    public function getSurname()
    {
        return $this->surname;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return Person
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->address = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add address
     *
     * @param \AdressBookBundle\Entity\Address $address
     * @return Person
     */
    public function addAddress(\AdressBookBundle\Entity\Address $address)
    {
        $this->address[] = $address;

        return $this;
    }

    /**
     * Remove address
     *
     * @param \AdressBookBundle\Entity\Address $address
     */
    public function removeAddress(\AdressBookBundle\Entity\Address $address)
    {
        $this->address->removeElement($address);
    }

    /**
     * Get address
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getAddress()
    {
        return $this->address;
    }
}

Address:

<?php

namespace AdressBookBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use AdressBookBundle\Entity\Person;

/**
 * Address
 *
 * @ORM\Table(name="address")
 * @ORM\Entity(repositoryClass="AdressBookBundle\Repository\AddressRepository")
 */
class Address
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="city", type="text")
     */
    private $city;

    /**
     * @var string
     *
     * @ORM\Column(name="street", type="text")
     */
    private $street;

    /**
     * @var int
     *
     * @ORM\Column(name="house_number", type="integer")
     */
    private $houseNumber;

    /**
     * @var int
     *
     * @ORM\Column(name="house_unit_number", type="integer")
     */
    private $houseUnitNumber;

    /**
     * $@ORM\ManyToOne(targetEntity="Person", inversedBy="address")
     * @ORM\JoinColumn(name="person_id", referencedColumnName="id")
     */
    private $person;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set city
     *
     * @param string $city
     * @return Address
     */
    public function setCity($city)
    {
        $this->city = $city;

        return $this;
    }

    /**
     * Get city
     *
     * @return string
     */
    public function getCity()
    {
        return $this->city;
    }

    /**
     * Set street
     *
     * @param string $street
     * @return Address
     */
    public function setStreet($street)
    {
        $this->street = $street;

        return $this;
    }

    /**
     * Get street
     *
     * @return string
     */
    public function getStreet()
    {
        return $this->street;
    }

    /**
     * Set houseNumber
     *
     * @param integer $houseNumber
     * @return Address
     */
    public function setHouseNumber($houseNumber)
    {
        $this->houseNumber = $houseNumber;

        return $this;
    }

    /**
     * Get houseNumber
     *
     * @return integer
     */
    public function getHouseNumber()
    {
        return $this->houseNumber;
    }

    /**
     * Set houseUnitNumber
     *
     * @param integer $houseUnitNumber
     * @return Address
     */
    public function setHouseUnitNumber($houseUnitNumber)
    {
        $this->houseUnitNumber = $houseUnitNumber;

        return $this;
    }

    /**
     * Get houseUnitNumber
     *
     * @return integer
     */
    public function getHouseUnitNumber()
    {
        return $this->houseUnitNumber;
    }
}

Could You please explain me how it excactly works?
As I understand I create relation by:

/**
     * $@ORM\ManyToOne(targetEntity="Person", inversedBy="address")
     * @ORM\JoinColumn(name="person_id", referencedColumnName="id")
*/

And than neew column person_id is creating in Address table. Am I right?


问:
php running calendar within two weeks
I have a calendar that shows the current month, which we use for scheduling. A request was made to have today's date in the middle, with two weeks of dates on either side.

Current code:

```<code><!DOCTYPE html>
<html>
<head>
<title>Running calendar</title>
</head>
<body>
<?php
date_default_timezone_set('America/New_York');

//Get today's date
$date = time();

//Break date into separate values
$day = date('d',$date);
$month = date('m',$date);
$year = date('Y',$date);

//Generate first day of the month
$first_day = mktime(0,0,0,$month,1,$year);

//Grab month name
$title = date('F',$first_day);

//Here you find out what day of the week the first day of the month falls on
$day_of_week = date('D', $first_day) ;

//We then determine how many days are in the current month
$days_in_month = cal_days_in_month(0, $month, $year) ;

switch($GLOBALS['day_of_week'])
{
case "Sun": $blank = 0; break;
case "Mon": $blank = 1; break;
case "Tue": $blank = 2; break;
case "Wed": $blank = 3; break;
case "Thu": $blank = 4; break;
case "Fri": $blank = 5; break;
case "Sat": $blank = 6; break;
}

$currHour = date("H");

echo "<div id=container>";
echo "<table width=100% class=calendar>";
echo "<tr><th colspan=32 id=title>$title $year</th></tr>";
echo "<tr><th>Employee</th>";
$day_num=1;
while($day_num <= $days_in_month){
echo "<th align=center ";
if($day == $day_num){echo "id=day";}
echo ">$day_num</th>";
$day_num++;
}
echo "</tr>";
echo "</table>";
echo "</div>";
?>
</body>
</html>
</code>```

What they would like to see:

21 22 23 24 25 26 27 28 29 30 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

I haven't had any luck getting the code figured out to display the past two weeks properly.

答:
You only need to change the way you calculate the start-date and optionally the number of days you want to display.

For the start date, just change this:

```<code>$first_day = mktime(0,0,0,$month,1,$year);
</code>```

to:

```<code>// Substract 14 days from the $date
$first_day = $date - (60 * 60 * 24 * 14);
</code>```

And you need to change your while loop to start at this date and run 28 (?) times.

Title: php running calendar within two weeks

Body:
I have a calendar that shows the current month, which we use for scheduling. A request was made to have today's date in the middle, with two weeks of dates on either side.

Current code:

<!DOCTYPE html>

<title>Running calendar</title>

<?php
date_default_timezone_set('America/New_York');

//Get today's date
$date = time();

//Break date into separate values
$day = date('d',$date);
$month = date('m',$date);
$year = date('Y',$date);

//Generate first day of the month
$first_day = mktime(0,0,0,$month,1,$year);

//Grab month name
$title = date('F',$first_day);

//Here you find out what day of the week the first day of the month falls on
$day_of_week = date('D', $first_day) ;

//We then determine how many days are in the current month
$days_in_month = cal_days_in_month(0, $month, $year) ;

switch($GLOBALS['day_of_week'])
{
case "Sun": $blank = 0; break;
case "Mon": $blank = 1; break;
case "Tue": $blank = 2; break;
case "Wed": $blank = 3; break;
case "Thu": $blank = 4; break;
case "Fri": $blank = 5; break;
case "Sat": $blank = 6; break;
}

$currHour = date("H");

echo "
";
echo "
";
echo "
$title $year
";
echo "
Employee	";
$day_num=1;
while($day_num <= $days_in_month){
echo "$day_num	";
$day_num++;
}
echo "
";
echo "
";
echo "
";
?>

What they would like to see:

21 22 23 24 25 26 27 28 29 30 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

I haven't had any luck getting the code figured out to display the past two weeks properly.

Body:
You only need to change the way you calculate the start-date and optionally the number of days you want to display.

For the start date, just change this:

$first_day = mktime(0,0,0,$month,1,$year);

to:

// Substract 14 days from the $date
$first_day = $date - (60 * 60 * 24 * 14);

And you need to change your while loop to start at this date and run 28 (?) times.