问:
Python RSA file encrypt-decrypt result varies with large files
I know that RSA can't encrypt more than 128 bytes at a time (modulus), so I am encrypting and decrypting the file in chunks. However, if my file is larger than a few kb, the result changes everytime I run the program. Sometimes the whole file is encrypted and decrypted correctly. Sometimes only the first 100 lines, etc. At this point I'm wondering if it's a reliability issue with the Crypto.PublicKey.RSA module. Here's my code:

```<code>def encrypt(file, public_key):
    read_size = 128
    with open(file, 'rb') as original_file:
        e_file = file + '.e'
        with open(e_file, 'wb') as encrypted_file:
            while True:
                file_part = original_file.read(read_size)

                if len(filePart) == 0:
                    break

                encrypted_file.write(public_key.encrypt(file_part, None)[0])

    os.remove(file)

def decrypt(file, private_key):
    read_size = 128
    with open(file, 'rb') as encrypted_file:
        d_file = file[:-2]
        with open(d_file, 'wb') as decrypted_file:
            while True:
                file_part = encrypted_file.read(read_size)

                if len(filePart) == 0:
                    break

                decrypted_file.write(private_key.decrypt(file_part))

    os.remove(file)

private_key = RSA.generate(1024)
public_key = RSA.importKey(private_key.publickey().exportKey())
my_file = 'myfile.txt'
encrypt(my_file, public_key)
decrypt(my_file + '.e', private_key)
</code>```

EDIT:: Maarten's answer is valid. Here is a concrete example of how I solved my problem with his answer.
I used this import:

```<code>from Crypto.Cipher import PKCS1_OAEP
</code>```

Then instead of using directly the public key to encrypt, I used this:

```<code>cipher = PKCS1_OAEP.new(publicKey)
encryptedFile.write(cipher.encrypt(filePart))
</code>```

I then did something similar for decryption.

答:
RSA requires padding to be secure, such as OAEP or the older, less secure PKCS#1 v1.5 padding. These bring some overhead. In general this is not as big an issue as a hybrid cryptosystem is often used, where RSA is paired with a symmetric cipher. Good choices would be RSA-OAEP and AES-GCM - and you may want to sign the plaintext first as well.

If you use raw RSA then you may run into trouble if the most significant bits (on the left, RSA uses big endian / network order) are set. In that case the plaintext will be considered identical to the plaintext modulus N, the modulus used within the RSA calculation.

So for example 4 % 5 = 4 but 9 % 5 is also 4). And when you perform the decryption the answer will be 4 even if the input was 9. So depending on the first (few) bits of the plaintext block all the bits will be flipped after decryption.

Body:
I know that RSA can't encrypt more than 128 bytes at a time (modulus), so I am encrypting and decrypting the file in chunks. However, if my file is larger than a few kb, the result changes everytime I run the program. Sometimes the whole file is encrypted and decrypted correctly. Sometimes only the first 100 lines, etc. At this point I'm wondering if it's a reliability issue with the Crypto.PublicKey.RSA module. Here's my code:

def encrypt(file, public_key):
    read_size = 128
    with open(file, 'rb') as original_file:
        e_file = file + '.e'
        with open(e_file, 'wb') as encrypted_file:
            while True:
                file_part = original_file.read(read_size)

                if len(filePart) == 0:
                    break

                encrypted_file.write(public_key.encrypt(file_part, None)[0])

    os.remove(file)

def decrypt(file, private_key):
    read_size = 128
    with open(file, 'rb') as encrypted_file:
        d_file = file[:-2]
        with open(d_file, 'wb') as decrypted_file:
            while True:
                file_part = encrypted_file.read(read_size)

                if len(filePart) == 0:
                    break

                decrypted_file.write(private_key.decrypt(file_part))

    os.remove(file)

private_key = RSA.generate(1024)
public_key = RSA.importKey(private_key.publickey().exportKey())
my_file = 'myfile.txt'
encrypt(my_file, public_key)
decrypt(my_file + '.e', private_key)

EDIT:: Maarten's answer is valid. Here is a concrete example of how I solved my problem with his answer.
I used this import:

from Crypto.Cipher import PKCS1_OAEP

Then instead of using directly the public key to encrypt, I used this:

cipher = PKCS1_OAEP.new(publicKey)
encryptedFile.write(cipher.encrypt(filePart))

I then did something similar for decryption.


来源: stackexchange

问:
Why can't I change the default set of filters for my reports?
In SAP Businesse Objects InfoView - Web Intelligence everytime a user runs a report the values for the default filters are the same.

But in the last few months something has changed and the default values are not the same I published initially.

Seems like somebody has changed the report but I can't see this in the changing log. There is no change there.

How can I change those settings without saving a new version of the report? Is it possible?

I'm using SAP BO 3.x

答: You shouldn't have to save a new version of the report (using Save As). Just refresh the report, using your preferred settings, and then save it over the old one.

ContentLicense: CC BY-SA 3.0


问:
RuntimeError: maximum recursion depth exceeded when parsing HTML
I have a test a program where I am trying to pull out all the text from each HTML tag. It seems to work until I override the __init__ function.

I get the error:

```<code> File "./html.py", line 9, in __init__
    TransParser.__init__(self)
  File "./html.py", line 9, in __init__
    TransParser.__init__(self)
  File "./html.py", line 9, in __init__
    TransParser.__init__(self)
  File "./html.py", line 9, in __init__
    TransParser.__init__(self)
RuntimeError: maximum recursion depth exceeded
</code>```

The program is here:

```<code>from HTMLParser import HTMLParser

trans = {
'History': 'History TRANSLATED',
'Acknowledgements': 'Acknowledgements TRANSLATED'
}

inputHTML = """<table border="0" cellspacing="0" cellpadding="0">
    <tbody>
      <tr>
        <td class="section-title"><a href="/about%20/history">History</a>        </td>

        <td class="section-title"><a href="/about/team">Project Team</a></td>

        <td class="section-title"><a href="/about/data">Contributors of data</a></td>

        <td class="section-title"><a href=
        "/about/acknowledgements">Acknowledgements</a></td>

        <td class="section-title"><a href="/about/origins">African Origins
        Project</a></td>

        <td class="section-title"><a href="/about/contacts">Contact us</a></td>
      </tr>
    </tbody>
  </table>

  <table border="0" cellspacing="0" cellpadding="0">
    <tbody>
      <tr>
        <td class="section-desc">A brief account of the origins of a single multi-source
        dataset of the trans-Atlantic slave trade and its realization first as a CD-ROM
        published by Cambridge University Press in 1999 and now, in an expanded version,
        on the Voyages website.</td>

        <td class="section-desc">Names of the principal investigators, of members of the
        project development team, and of individuals serving on the steering committee
        and advisory board.</td>

        <td class="section-desc">Names of scholars and researchers whose findings on the
       trans-Atlantic slave trade have been incorporated into the Voyages Database.</td>

        <td class="section-desc">Major sponsors and institutional partners of the Voyages
        website, as well as other organizations and individuals who have assisted the
        work of the project team.</td>

        <td class="section-desc">A scholar-public collaborative project using audio
        recordings of names in African Names Database to trace the geographic origins of
         Africans transported in the transatlantic slave trade.</td>

        <td class="section-desc">Members of the Voyages editorial board and the email
         address for contacting the website.</td>
      </tr>
     </tbody>
  </table>"""

class TransParser(HTMLParser):
    def __init__(self):
        TransParser.__init__(self)
        self.trans_data = self.rawdata

    def handle_data(self, data):
         data = data.strip()
        if data:
            section = trans.get(data, data)
            #self.trans_data = self.trans_data.replace(data, section)

parser = TransParser()
parser.feed(inputHTML)
</code>```

答:
```<code>class TransParser(HTMLParser):
    def __init__(self):
        TransParser.__init__(self)
        #         ^^^ You are calling the same constructor recursively.
</code>```

Fix:

```<code>class TransParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        ..
        ..
</code>```

Body:
I have a test a program where I am trying to pull out all the text from each HTML tag. It seems to work until I override the __init__ function.

I get the error:

 File "./html.py", line 9, in __init__
    TransParser.__init__(self)
  File "./html.py", line 9, in __init__
    TransParser.__init__(self)
  File "./html.py", line 9, in __init__
    TransParser.__init__(self)
  File "./html.py", line 9, in __init__
    TransParser.__init__(self)
RuntimeError: maximum recursion depth exceeded

The program is here:

from HTMLParser import HTMLParser

trans = {
'History': 'History TRANSLATED',
'Acknowledgements': 'Acknowledgements TRANSLATED'
}

inputHTML = """

        History

        Project Team

        Contributors of data

        Acknowledgements

        African Origins
        Project

        Contact us

        A brief account of the origins of a single multi-source
        dataset of the trans-Atlantic slave trade and its realization first as a CD-ROM
        published by Cambridge University Press in 1999 and now, in an expanded version,
        on the Voyages website.

        Names of the principal investigators, of members of the
        project development team, and of individuals serving on the steering committee
        and advisory board.

        Names of scholars and researchers whose findings on the
       trans-Atlantic slave trade have been incorporated into the Voyages Database.

        Major sponsors and institutional partners of the Voyages
        website, as well as other organizations and individuals who have assisted the
        work of the project team.

        A scholar-public collaborative project using audio
        recordings of names in African Names Database to trace the geographic origins of
         Africans transported in the transatlantic slave trade.

        Members of the Voyages editorial board and the email
         address for contacting the website.

"""

class TransParser(HTMLParser):
    def __init__(self):
        TransParser.__init__(self)
        self.trans_data = self.rawdata

    def handle_data(self, data):
         data = data.strip()
        if data:
            section = trans.get(data, data)
            #self.trans_data = self.trans_data.replace(data, section)

parser = TransParser()
parser.feed(inputHTML)

Body:
class TransParser(HTMLParser):
    def __init__(self):
        TransParser.__init__(self)
        #         ^^^ You are calling the same constructor recursively.

Fix:

class TransParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        ..
        ..


问:
Approaches to Serializing an Object Graph with Circular References
Let's suppose that I want to implement a serializer (C#) for the sake of practice, and I would want the said serializer to not fail on circular references.

The apparent solution would be to only serialize objects which were not yet encountered and skipping objects which were. This is easily accomplished by hashing the instances (in one way or another).

The proposed solution bids the question: "What defines an object's identity?"
One would say - leave it up to the GetHashCode and Equals methods.
This is an acceptable solution- which conserves time on serialization and conserves memory on de-serialization.

However, this is not always a desirable outcome, since many instances may have the same identity yet used for completely different things in the serialized domain, so that de-serializing them later on as the same instance would violate the domain logic.

So, as an author of such a serializer, I must leave it up to the caller to make such decisions.

One approach to solve this would be to Hash a collection per the said type, and distinguishing between serialized and non serialized instances by iterating the collection and invoking ReferenceEquals on each contained element.
This works, but is sub-optimal - performance wise.

Another approach is to Pin objects in the unmanaged heap, and use the pinned object address as an identity, which seems kind of an overkill and has a lot of overhead as well.

Another approach is to use reflection to invoke the Object.Equals and Object.GetHashCode default implementations of every instance- which seems to solve the problem, but has its own little overhead.

My questions are:

1)Are there any caveats which I have missed to the approaches I've suggested?

2)Are there any more additional approaches which I might have not thought of?

答:
Take a look at System.Runtime.Serialization.ObjectIDGenerator. It does exactly that.

According to the MSDN page:

Using a hash table, the ObjectIDGenerator retains which ID is assigned to which object. The object references, which uniquely identify each object, are addresses in the runtime garbage-collected heap. Object reference values can change during serialization, but the table is updated automatically so the information is correct.

The source code is also available here.


答:
```<code>class TransParser(HTMLParser):
    def __init__(self):
        TransParser.__init__(self)
        self.trans_data = self.rawdata
</code>```

What are you trying to do here?  The init method calls itself; this is infinite recursion.  Do you mean to call the parent's init method, perhaps?  That would be

```<code>        super().__init__(self)
</code>```

Title: RuntimeError: maximum recursion depth exceeded when parsing HTML

Body:
class TransParser(HTMLParser):
    def __init__(self):
        TransParser.__init__(self)
        self.trans_data = self.rawdata

What are you trying to do here?  The init method calls itself; this is infinite recursion.  Do you mean to call the parent's init method, perhaps?  That would be

        super().__init__(self)


问:
What's the easiest way to run a .js javascript file on windows?
When you try and run (not edit) a Javascript file, It will give an error that sounds like it is missing a reference in your code.  For Example, I got:

```<code>Line: 3 Char: 1

Error: 'document' is undefined'

Code: 800A1391

Source: Microsoft JScript runtime error
</code>```

Is it trying to execute a program similar to VBScript?  Should I be running it with another program?

答:
The easiest way to "run a JS File" is to create an HTML file that references the JS file and let the default browser run it.  An example of a simple HTML file that would do this (assuming the script was named script.js and in the same folder as the html file (named script.html):

```<code><html>
  <head>
   <title>My Script</title>
   <script src='script.js'></script>
  </head>
  <body></body>
</html>
</code>```

As a side note, on windows you could name your html file script.hta and it will open in Internet Explorer and in a window without an address bar (https://en.wikipedia.org/wiki/HTML_Application), depending on your environment this might be a tad easier.

Body:
When you try and run (not edit) a Javascript file, It will give an error that sounds like it is missing a reference in your code.  For Example, I got:

Line: 3 Char: 1

Error: 'document' is undefined'

Code: 800A1391

Source: Microsoft JScript runtime error

Is it trying to execute a program similar to VBScript?  Should I be running it with another program?

Body:
The easiest way to "run a JS File" is to create an HTML file that references the JS file and let the default browser run it.  An example of a simple HTML file that would do this (assuming the script was named script.js and in the same folder as the html file (named script.html):

<html>
  <head>
   <title>My Script</title>
   <script src='script.js'></script>
  </head>
  <body></body>
</html>

As a side note, on windows you could name your html file script.hta and it will open in Internet Explorer and in a window without an address bar (https://en.wikipedia.org/wiki/HTML_Application), depending on your environment this might be a tad easier.


问:
Share files between host system and docker container using specific UID
I'm trying to share files within a Docker guest using the volume sharing.  In order to get the same UID, and therefore interoperability with those files, I would like to create a user in the Docker guest with the same UID as my own user.

In order to test out the idea, I wrote the following simplistic Dockerfile:

```<code>FROM phusion/baseimage

RUN touch /root/uid-$UID
</code>```

Testing it with docker build -t=docktest . and then docker run docktest ls -al /root reveals that the file is simply named uid-.

Is there a means to share host environment variables with Docker during the guest build process?

答:
I slightly modified @ISanych answer:

```<code>#!/usr/bin/env bash

user_exists() {
  id -u $1 > /dev/null 2>&1
}

group_exists() {
  id -g $1 > /dev/null 2>&1
}

setuser() {
  if [[ "$#" != 3 ]]; then
    echo "Usage: $0 <path> <user> <group>"
    return
  fi
  local dest_uid=$(stat -c "%u" $1)
  local dest_gid=$(stat -c "%g" $1)
  if user_exists $dest_uid; then
    id -nu $dest_uid
    return
  fi
  local dest_user=$2
  local dest_group=$3

  if user_exists $dest_user; then
    userdel $dest_user
  fi

  if group_exists $dest_group; then
    groupdel $dest_user
  fi

  groupadd -g $dest_gid $dest_group
  useradd -u $dest_uid -g $dest_gid -s $DEFAULT_SHELL -d $DEFAULT_HOME -G root $dest_user
  chown -R $dest_uid:$dest_gid $DEFAULT_HOME
  id -nu $dest_user
}

REAL_USER=$(setuser $SRC_DIR $DEFAULT_USER $DEFAULT_GROUP)
</code>```

setuser function accepts user and group names that you want to assign to uid and gid of provided directory. Then if user with such uid exists then it simply returns login corresponding to this uid, otherwise it creates user and group and returns login originally passed to function.

So you get the login of user that owns destination directory.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to share files within a Docker guest using the volume sharing.  In order to get the same UID, and therefore interoperability with those files, I would like to create a user in the Docker guest with the same UID as my own user.

In order to test out the idea, I wrote the following simplistic Dockerfile:

FROM phusion/baseimage

RUN touch /root/uid-$UID

Testing it with docker build -t=docktest . and then docker run docktest ls -al /root reveals that the file is simply named uid-.

Is there a means to share host environment variables with Docker during the guest build process?

Body:
I slightly modified @ISanych answer:

#!/usr/bin/env bash

user_exists() {
  id -u $1 > /dev/null 2>&1
}

group_exists() {
  id -g $1 > /dev/null 2>&1
}

setuser() {
  if [[ "$#" != 3 ]]; then
    echo "Usage: $0 <path> <user> <group>"
    return
  fi
  local dest_uid=$(stat -c "%u" $1)
  local dest_gid=$(stat -c "%g" $1)
  if user_exists $dest_uid; then
    id -nu $dest_uid
    return
  fi
  local dest_user=$2
  local dest_group=$3

  if user_exists $dest_user; then
    userdel $dest_user
  fi

  if group_exists $dest_group; then
    groupdel $dest_user
  fi

  groupadd -g $dest_gid $dest_group
  useradd -u $dest_uid -g $dest_gid -s $DEFAULT_SHELL -d $DEFAULT_HOME -G root $dest_user
  chown -R $dest_uid:$dest_gid $DEFAULT_HOME
  id -nu $dest_user
}

REAL_USER=$(setuser $SRC_DIR $DEFAULT_USER $DEFAULT_GROUP)

setuser function accepts user and group names that you want to assign to uid and gid of provided directory. Then if user with such uid exists then it simply returns login corresponding to this uid, otherwise it creates user and group and returns login originally passed to function.

So you get the login of user that owns destination directory.


问:
Eat memory using Python
I am trying to create an app that can "Purposely" consume RAM as much as we specify immediately.
e.g. I want to consume 512 MB RAM, then the app will consume 512 MB directly.

I have search on the web, most of them are using while loop to fill the ram with variable or data. But I think it is slow way to fill the RAM and might not accurate either.

I am looking for a library in python about memory management. and came across these http://docs.python.org/library/mmap.html. But can't figure out how to use these library to eat the RAM Space in one shot.

I ever saw an mem-eater application, but don't know how they were written...

So, is there any other better suggestion for Fill the RAM with random data immediately?
Or Should I just use while loop to fill the data manually but with Multi-Threading to make it faster?

答:
Here is a version of markolopa's answer that worked for me:</p>
```<code>import os
import psutil

PROCESS = psutil.Process(os.getpid())
MEGA = 10 ** 6
MEGA_STR = ' ' * MEGA

def pmem():
    try:
        tot, avail, percent, used, free, active, inactive, buffers = psutil.virtual_memory()
    except ValueError:
        tot, avail, percent, used, free, active, inactive, buffers, cached, shared = psutil.virtual_memory()
    tot, avail, used, free = tot / MEGA, avail / MEGA, used / MEGA, free / MEGA
    proc = PROCESS.memory_info()[1] / MEGA
    print('process = %s total = %s avail = %s used = %s free = %s percent = %s'
          % (proc, tot, avail, used, free, percent))

def alloc_max_array():
    i = 0
    ar = []
    while True:
        try:
            #ar.append(MEGA_STR)  # no copy if reusing the same string!
            ar.append(MEGA_STR + str(i))
        except MemoryError:
            break
        i += 1
    max_i = i - 1
    print('maximum array allocation:', max_i)
    pmem()

def alloc_max_str():
    i = 0
    while True:
        try:
            a = ' ' * (i * 10 * MEGA)
            del a
        except MemoryError:
            break
        i += 1
    max_i = i - 1
    _ = ' ' * (max_i * 10 * MEGA)
    print('maximum string allocation', max_i)
    pmem()

pmem()
alloc_max_str()
alloc_max_array()
</code>```

Title: Eat memory using Python

Body:
Here is a version of markolopa's answer that worked for me:

import os
import psutil

PROCESS = psutil.Process(os.getpid())
MEGA = 10 ** 6
MEGA_STR = ' ' * MEGA

def pmem():
    try:
        tot, avail, percent, used, free, active, inactive, buffers = psutil.virtual_memory()
    except ValueError:
        tot, avail, percent, used, free, active, inactive, buffers, cached, shared = psutil.virtual_memory()
    tot, avail, used, free = tot / MEGA, avail / MEGA, used / MEGA, free / MEGA
    proc = PROCESS.memory_info()[1] / MEGA
    print('process = %s total = %s avail = %s used = %s free = %s percent = %s'
          % (proc, tot, avail, used, free, percent))

def alloc_max_array():
    i = 0
    ar = []
    while True:
        try:
            #ar.append(MEGA_STR)  # no copy if reusing the same string!
            ar.append(MEGA_STR + str(i))
        except MemoryError:
            break
        i += 1
    max_i = i - 1
    print('maximum array allocation:', max_i)
    pmem()

def alloc_max_str():
    i = 0
    while True:
        try:
            a = ' ' * (i * 10 * MEGA)
            del a
        except MemoryError:
            break
        i += 1
    max_i = i - 1
    _ = ' ' * (max_i * 10 * MEGA)
    print('maximum string allocation', max_i)
    pmem()

pmem()
alloc_max_str()
alloc_max_array()


问:
Parse error: syntax error, unexpected '=>' > (T_DOUBLE_ARROW), expecting

I have this error message "Parse error: syntax error, unexpected '=>'
  (T_DOUBLE_ARROW), expecting ')'" , as I want to create 2D of array to pass the 2 keys into foreach loop .

```<code>$productIds = array
  (
  [0] => Array
        (
            [SKU] => 'xx'
            [Price] => 22

        )

    [1] => Array
        (
            [SKU] => 'bb',
            [Price] => 15,

        )

    [2] => Array
        (
            [SKU] => 'cc',
            [Price] => 5,

        )
    [3] => Array
        (
            [SKU] => 'tt',
            [Price] => 17,

        )
</code>```

答:
I think you are missing a comma in your array when you create that array, it should be:

```<code> Array
    (
        [SKU] => 'xx',
        [Price] => 22

    )
</code>```

Instead of

```<code> Array
    (
        [SKU] => 'xx'
        [Price] => 22

    )
</code>```

Body:
I have this error message "Parse error: syntax error, unexpected '=>'
  (T_DOUBLE_ARROW), expecting ')'" , as I want to create 2D of array to pass the 2 keys into foreach loop .

$productIds = array
  (
  [0] => Array
        (
            [SKU] => 'xx'
            [Price] => 22

        )

    [1] => Array
        (
            [SKU] => 'bb',
            [Price] => 15,

        )

    [2] => Array
        (
            [SKU] => 'cc',
            [Price] => 5,

        )
    [3] => Array
        (
            [SKU] => 'tt',
            [Price] => 17,

        )

Body:
I think you are missing a comma in your array when you create that array, it should be:

 Array
    (
        [SKU] => 'xx',
        [Price] => 22

    )

Instead of

 Array
    (
        [SKU] => 'xx'
        [Price] => 22

    )


问:
Where to find JavaScript documentation?
I think theres one https://developer.mozilla.org/en/JavaScript/Reference but for for things like what properties/functions a Textarea object will have, where can I get it?

I know textarea have properties like selectionStart, selectionEnd but what others? where can I find that info?

答:
The Gecko DOM Reference is pretty complete.

For the dark side (IE-specific stuff), there's also Microsoft's HTML and DHTML Reference

And for cross-browser advice, consult QuirksMode (thanks Raynos)

ContentLicense: CC BY-SA 2.5

Title: Where to find JavaScript documentation?


问:
Store data in Custom Fields or attachment in ics iCal file
I need to give my manually built iCal file (.ics) some additional infos which I actually don't want to be visible for Calendar app users. Thus I need to be able to set them manually when creating an Event in an iOS application and (later) reading them from the Calendar events.

I was wondering whether it is possible to add custom fields / attributes to a iCal / .ics file itself (not by using a calendar application!). They shall not be displayed in a Calendar application but accessible for me as a mobile app developer to store IDs, references, anything when I read them out from a calendar on the device... Until now the only possibility seems to be storing those vales as description / notes, but I'm definitely not happy with that!
Is there any possibilltity? Neither could I achieve it by now nor did I find anything useful on the internet...

As an alternative, I was thinking about using the Attachment function of iCal, which - unfortunately - is visible for invited persons and the organizer himself and may not be editable / updated when edited...

Thanks in advance!

Below: ics example date

```<code>BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Apple Inc.//Mac OS X 10.12.2//EN
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:Europe/Berlin
BEGIN:DAYLIGHT
TZOFFSETFROM:+0100
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
DTSTART:19810329T020000
TZNAME:MESZ
TZOFFSETTO:+0200
END:DAYLIGHT
BEGIN:STANDARD
TZOFFSETFROM:+0200
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
DTSTART:19961027T030000
TZNAME:MEZ
TZOFFSETTO:+0100
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
CREATED:20170330T114118Z
UID:38F0C7FE-9711-437F-A5FE-E670E97C6766
DTEND;TZID=Europe/Berlin:20170330T160000
TRANSP:OPAQUE
ATTENDEE;CN="John Doe";CUTYPE=INDIVIDUAL;EMAIL="john@doe.de";PAR
 TSTAT=NEEDS-ACTION;ROLE=REQ-PARTICIPANT;RSVP=TRUE:mailto:john@doe.de
X-APPLE-TRAVEL-ADVISORY-BEHAVIOR:AUTOMATIC
SUMMARY:iCal Test100

CUSTOM:*** WHAT I WOULD NEED ***

DTSTART;TZID=Europe/Berlin:20170330T153000
DTSTAMP:20170330T114208Z
ORGANIZER;CN="Jon Doh":mailto:Jon@Doh.de
SEQUENCE:0
END:VEVENT
END:VCALENDAR
</code>```

答:
You can define your own properties and parameters.  Just make sure they start with "X-".  For example:</p>

```<code>BEGIN:VEVENT
UID;X-FOO=bar:38F0C7FE-9711-437F-A5FE-E670E97C6766
X-SUPER-SECRET:abc123
...
END:VEVENT
</code>```

Body:
I need to give my manually built iCal file (.ics) some additional infos which I actually don't want to be visible for Calendar app users. Thus I need to be able to set them manually when creating an Event in an iOS application and (later) reading them from the Calendar events.

I was wondering whether it is possible to add custom fields / attributes to a iCal / .ics file itself (not by using a calendar application!). They shall not be displayed in a Calendar application but accessible for me as a mobile app developer to store IDs, references, anything when I read them out from a calendar on the device... Until now the only possibility seems to be storing those vales as description / notes, but I'm definitely not happy with that!
Is there any possibilltity? Neither could I achieve it by now nor did I find anything useful on the internet...

As an alternative, I was thinking about using the Attachment function of iCal, which - unfortunately - is visible for invited persons and the organizer himself and may not be editable / updated when edited...

Thanks in advance!

Below: ics example date

BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Apple Inc.//Mac OS X 10.12.2//EN
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:Europe/Berlin
BEGIN:DAYLIGHT
TZOFFSETFROM:+0100
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
DTSTART:19810329T020000
TZNAME:MESZ
TZOFFSETTO:+0200
END:DAYLIGHT
BEGIN:STANDARD
TZOFFSETFROM:+0200
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
DTSTART:19961027T030000
TZNAME:MEZ
TZOFFSETTO:+0100
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
CREATED:20170330T114118Z
UID:38F0C7FE-9711-437F-A5FE-E670E97C6766
DTEND;TZID=Europe/Berlin:20170330T160000
TRANSP:OPAQUE
ATTENDEE;CN="John Doe";CUTYPE=INDIVIDUAL;EMAIL="john@doe.de";PAR
 TSTAT=NEEDS-ACTION;ROLE=REQ-PARTICIPANT;RSVP=TRUE:mailto:john@doe.de
X-APPLE-TRAVEL-ADVISORY-BEHAVIOR:AUTOMATIC
SUMMARY:iCal Test100

CUSTOM:*** WHAT I WOULD NEED ***

DTSTART;TZID=Europe/Berlin:20170330T153000
DTSTAMP:20170330T114208Z
ORGANIZER;CN="Jon Doh":mailto:Jon@Doh.de
SEQUENCE:0
END:VEVENT
END:VCALENDAR

Body:
You can define your own properties and parameters.  Just make sure they start with "X-".  For example:

BEGIN:VEVENT
UID;X-FOO=bar:38F0C7FE-9711-437F-A5FE-E670E97C6766
X-SUPER-SECRET:abc123
...
END:VEVENT


问:
Google App Engine access API Service trough VPN
Can I create a VPN on Google Cloud Platform and access private content trough this VPN on Google App Engine? I know this can be done trough Google Compute Engine, but this is not what I want.

All of my project is on Google App Engine and I use urlfetch to get external addresses and services. Will the VPN provide some kind of path/url/ip that I can access with urlfetch to get the content accessible trough the VPN?

答: You can do this on the flexible environment today, because that uses the underlying Compute Engine infrastructure. The standard environment doesn't yet connect to the Compute Engine network, but this is an interesting use case that we'll be thinking about.</p>


问:
Building dll without statically linking
I've got project A and project B as part of a solution. Project A is dependent on project B, because it uses classes from project B. The easiest way to build a dll, is to put the two together, and build one dll out of that. Now assume, Project B gets updated every week or so.

Because of those regular updates, I would prefer to just build a dll for project A and use the source code of project B in the solution. So is there a way to achieve this, to build a dll and reference the "missing" files (files from project B) without statically linking them?
Note: I want project B to stay as source code and not be a dll

答:
Yes - use a "Project Reference" in Visual Studio - it will update your build process so Project A is built after Project B, and Project A will also always have the latest IntelliSense on Project B.

https://msdn.microsoft.com/en-us/library/wkze6zky(v=vs.120).aspx

Title: Building dll without statically linking


问:
Cannot find name 'require' after upgrading to Angular4
I want to use Chart.js within my Angular project.
In previous Angular2 versions, I have been doing this well by using a 'chart.loader.ts' which has:

```<code>export const { Chart } = require('chart.js');
</code>```

Then in the component code I just

```<code>import { Chart } from './chart.loader';
</code>```

But after upgrading to cli 1.0.0 and Angular 4, I get the error: "Cannot find name 'require'".

To reproduce the error:

```<code>ng new newapp
cd newapp
npm install chart.js --save
echo "export const { Chart } = require('chart.js');" >> src/app/chart.loader.ts
ng serve
</code>```

In my 'tsconfig.json', I have

```<code>"typeRoots": [
  "node_modules/@types"
],
</code>```

And in 'node_modules/@types/node/index.d.ts' there is:

```<code>declare var require: NodeRequire;
</code>```

So I'm confused.

BTW, I constantly encounter the warning:

```<code>[tslint] The selector of the component "OverviewComponent" should have prefix "app"(component-selector)
</code>```

Though I have set the "prefix": "" in my '.angular-cli.json'. Could it because changing from 'angular-cli.json' to '.angular-cli.json' the cause?

答:
The problem (as outlined in typescript getting error TS2304: cannot find name ' require') is that the type definitions for node are not installed.

With a projected genned with @angular/cli 1.x, the specific steps should be:

Step 1:

Install @types/node with either of the following:

```<code>- npm install --save @types/node
- yarn add @types/node -D
</code>```

Step 2:
Edit your src/tsconfig.app.json file and add the following in place of the empty "types": [], which should already be there:

```<code>...
"types": [ "node" ],
"typeRoots": [ "../node_modules/@types" ]
...
</code>```

If I've missed anything, jot a comment and I'll edit my answer.

Body:
I want to use Chart.js within my Angular project.
In previous Angular2 versions, I have been doing this well by using a 'chart.loader.ts' which has:

export const { Chart } = require('chart.js');

Then in the component code I just

import { Chart } from './chart.loader';

But after upgrading to cli 1.0.0 and Angular 4, I get the error: "Cannot find name 'require'".

To reproduce the error:

ng new newapp
cd newapp
npm install chart.js --save
echo "export const { Chart } = require('chart.js');" >> src/app/chart.loader.ts
ng serve

In my 'tsconfig.json', I have

"typeRoots": [
  "node_modules/@types"
],

And in 'node_modules/@types/node/index.d.ts' there is:

declare var require: NodeRequire;

So I'm confused.

BTW, I constantly encounter the warning:

[tslint] The selector of the component "OverviewComponent" should have prefix "app"(component-selector)

Though I have set the "prefix": "" in my '.angular-cli.json'. Could it because changing from 'angular-cli.json' to '.angular-cli.json' the cause?

Body:
The problem (as outlined in typescript getting error TS2304: cannot find name ' require') is that the type definitions for node are not installed.

With a projected genned with @angular/cli 1.x, the specific steps should be:

Step 1:

Install @types/node with either of the following:

- npm install --save @types/node
- yarn add @types/node -D

Step 2:
Edit your src/tsconfig.app.json file and add the following in place of the empty "types": [], which should already be there:

...
"types": [ "node" ],
"typeRoots": [ "../node_modules/@types" ]
...

If I've missed anything, jot a comment and I'll edit my answer.


问:
What does Failure of Web server exactly mean?
What really happens when the web server fails ? I know the usual thing that the Website will be down and the page I have requested is inaccessible.

The cause might be external like too many incoming requests but what really happens in the inner workings of the server that leads to such a condition ?

答: I might be congestion due to lack of bandwidth or the VM/server that is containing the info/web page </p>


问:
Laravel 5 - Interface is not instantiable
I know that this question was asked so many times, but none of answers helped me.

I'm getting exception in Laravel 5

```<code>BindingResolutionException in Container.php line 785:
Target [App\Contracts\CustomModelInterface] is not instantiable.
</code>```

What I've done without success:

Register App\Providers\AppRepositoryProvider in app.php providers

php artisan clear-compiled

Everything works if I replace interfaces on repositories in MyService, but I feel that it's wrong (should it be handled by IoC container?).

Structure:

```<code>app
  - Contracts
    - CustomModelInterface.php
  - Models
    - CustomModel.php
  - Repositories
    - CustomModelRepository.php
  - Providers
    - AppRepositoryProvider.php
  - Services
    - MyService.php
</code>```

App\Contracts\CustomModelInterface.php

```<code><?php namespace App\Contracts;

interface CustomModelInterface {
    public function get();
}
</code>```

App\Repositories\CustomModelRepository.php

```<code><?php namespace App\Repositories;

use App\Contracts\CustomModelInterface;
use App\Models\CustomModel;

class CustomModelRepository implements CustomModelInterface {

    private $Model;

    public function __construct(CustomModel $model) {
        $this->Model = $model;
    }

    public function get() {
        return 'result';
    }
}
</code>```

App\Services\MyService.php (Keep business logic / layer between controller and repositories)

```<code><?php namespace App\Services;

use App\Contracts\CustomModelInterface;

class MyService {

    private $Model;

    public function __construct(CustomModelInterface $customModel) {
        $this->Model= $customModel;
    }

    public function getAll() {
        return $this->Model->get();
    }
}
</code>```

App\Providers\AppRepositoryProvider.php

```<code><?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppRepositoryProvider extends ServiceProvider {

    public function boot() {}

    public function register() {
        $models = array(
            'CustomModel'
        );

        foreach ($models as $idx => $model) {
            $this->app->bind("App\Contracts\{$model}Interface", "App\Repositories\{$model}Repository");
        }
    }
}
</code>```

My controller looks like:

```<code><?php namespace App\Http\Controllers;

use App\Services\MyService;

class SuperController extends Controller {

    private $My;

    public function __construct(MyService $myService) {
        $this->My = $myService;
    }

    public function getDetails() {
        return $this->My->getAll();
    }
}
</code>```

composer.json

```<code>"autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/",
            "App\\Models\\": "app/Models/",
            "App\\Contracts\\": "app/Contracts/",
            "App\\Repositories\\": "app/Repositories/"
        }
    },
</code>```

答:
Note that this can also be caused by the _constructor on the class being declared private, or otherwise being blocked...
If it cant call the constructor, the binding will fail</p>

Body:
I know that this question was asked so many times, but none of answers helped me.

I'm getting exception in Laravel 5

BindingResolutionException in Container.php line 785:
Target [App\Contracts\CustomModelInterface] is not instantiable.

What I've done without success:

Register App\Providers\AppRepositoryProvider in app.php providers

php artisan clear-compiled

Everything works if I replace interfaces on repositories in MyService, but I feel that it's wrong (should it be handled by IoC container?).

Structure:

app
  - Contracts
    - CustomModelInterface.php
  - Models
    - CustomModel.php
  - Repositories
    - CustomModelRepository.php
  - Providers
    - AppRepositoryProvider.php
  - Services
    - MyService.php

App\Contracts\CustomModelInterface.php

<?php namespace App\Contracts;

interface CustomModelInterface {
    public function get();
}

App\Repositories\CustomModelRepository.php

<?php namespace App\Repositories;

use App\Contracts\CustomModelInterface;
use App\Models\CustomModel;

class CustomModelRepository implements CustomModelInterface {

    private $Model;

    public function __construct(CustomModel $model) {
        $this->Model = $model;
    }

    public function get() {
        return 'result';
    }
}

App\Services\MyService.php (Keep business logic / layer between controller and repositories)

<?php namespace App\Services;

use App\Contracts\CustomModelInterface;

class MyService {

    private $Model;

    public function __construct(CustomModelInterface $customModel) {
        $this->Model= $customModel;
    }

    public function getAll() {
        return $this->Model->get();
    }
}

App\Providers\AppRepositoryProvider.php

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppRepositoryProvider extends ServiceProvider {

    public function boot() {}

    public function register() {
        $models = array(
            'CustomModel'
        );

        foreach ($models as $idx => $model) {
            $this->app->bind("App\Contracts\{$model}Interface", "App\Repositories\{$model}Repository");
        }
    }
}

My controller looks like:

<?php namespace App\Http\Controllers;

use App\Services\MyService;

class SuperController extends Controller {

    private $My;

    public function __construct(MyService $myService) {
        $this->My = $myService;
    }

    public function getDetails() {
        return $this->My->getAll();
    }
}

composer.json

"autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/",
            "App\\Models\\": "app/Models/",
            "App\\Contracts\\": "app/Contracts/",
            "App\\Repositories\\": "app/Repositories/"
        }
    },


问:
React-DatePicker updating state with previously selected date
I would like to update the state of a component when a date is selected from the React-DatePicker.  I am getting some odd behavior below.

Example of Current Behavior:

Component loads with empty date field

I select 3/28/2017 and get the following console log

main.ffde8a1f.js:8 it changed dates

main.ffde8a1f.js:8 date = 1490673600000

main.ffde8a1f.js:8 dueDate value =

Say then I select 3/22/2017 and get the following console log:

main.ffde8a1f.js:8 it changed dates

main.ffde8a1f.js:8 date = 1490155200000

main.ffde8a1f.js:8 dueDate value = 1490673600000

The second and third logs should have the same value.  Can anyone explain to me why this weird behavior is occurring?

MY ATTEMPT

Imports

```<code>import React from 'react';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import 'react-datepicker/dist/react-datepicker.css';
</code>```

Component

I set the state of dueDate to '' to begin.

```<code>export default class Request extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      dueDate: '',
    }

    this.handleChangeDate = this.handleChangeDate.bind(this);

  }
</code>```

Handle Date Selection

ISSUE
My handleChangeDate function will fire when a date is provided and the date in milliseconds will log to the console, but the dueDate is logged as being the previous value it should have been.

```<code> handleChangeDate(date) {
    console.log("it changed dates");
    console.log('date = ' + date);  //date in milliseconds logs properly
    this.setState({
      dueDate: date
    });
    console.log('dueDate value = ' + this.state.dueDate);  //date from state logs the previous value rather than its new value
  }
</code>```

Render

I am keeping the date picker simple at the moment to minimize potential bugs.  Only the selected date is passed in from the state and the handleChangeDate method for a selected date.

```<code>  render() {
    return (
      <div className="requestDetails">
        <h2>Due Date</h2>
        <DatePicker
           selected={this.state.dueDate}
           onChange={this.handleChangeDate}
        />
      </div>
    );
  }
}
</code>```

答:
this.setState is not guaranteed to be synchronous, because they can be processed in batches. This means that although you call console.log in your code after your setState, the state may not have actually changed yet.

From the React docs:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this
  method can potentially return the existing value. There is no
  guarantee of synchronous operation of calls to setState and calls may
  be batched for performance gains.

If you would like to check if your state is updated, you can either used a callback as the second argument to setState or put some logic in the shouldComponentUpdate(nextProps, nextState) lifecycle method.

Example:

```<code>handleChangeDate(date) {
  this.setState({
    dueDate: date
  }, () => console.log(this.state.dueDate)); // This will show the updated state when state is set.
}
</code>```

or

```<code>shouldComponentUpdate(nextProps, nextState) {
  if (this.state.dueDate !== nextState.dueDate) {
    console.log('dueDate:  ', nextState.dueDate);
  }
}
</code>```

setState Documentation: (Note the function signature, setState(nextState, callback))

https://facebook.github.io/react/docs/react-component.html#setstate

shouldComponentUpdate Documentation:

https://facebook.github.io/react/docs/react-component.html#shouldcomponentupdate

Body:
I would like to update the state of a component when a date is selected from the React-DatePicker.  I am getting some odd behavior below.

Example of Current Behavior:

Component loads with empty date field

I select 3/28/2017 and get the following console log

main.ffde8a1f.js:8 it changed dates

main.ffde8a1f.js:8 date = 1490673600000

main.ffde8a1f.js:8 dueDate value =

Say then I select 3/22/2017 and get the following console log:

main.ffde8a1f.js:8 it changed dates

main.ffde8a1f.js:8 date = 1490155200000

main.ffde8a1f.js:8 dueDate value = 1490673600000

The second and third logs should have the same value.  Can anyone explain to me why this weird behavior is occurring?

MY ATTEMPT

Imports

import React from 'react';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import 'react-datepicker/dist/react-datepicker.css';

Component

I set the state of dueDate to '' to begin.

export default class Request extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      dueDate: '',
    }

    this.handleChangeDate = this.handleChangeDate.bind(this);

  }

Handle Date Selection

ISSUE
My handleChangeDate function will fire when a date is provided and the date in milliseconds will log to the console, but the dueDate is logged as being the previous value it should have been.

 handleChangeDate(date) {
    console.log("it changed dates");
    console.log('date = ' + date);  //date in milliseconds logs properly
    this.setState({
      dueDate: date
    });
    console.log('dueDate value = ' + this.state.dueDate);  //date from state logs the previous value rather than its new value
  }

Render

I am keeping the date picker simple at the moment to minimize potential bugs.  Only the selected date is passed in from the state and the handleChangeDate method for a selected date.

  render() {
    return (

Due Date

        <DatePicker
           selected={this.state.dueDate}
           onChange={this.handleChangeDate}
        />

    );
  }
}

Body:
this.setState is not guaranteed to be synchronous, because they can be processed in batches. This means that although you call console.log in your code after your setState, the state may not have actually changed yet.

From the React docs:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this
  method can potentially return the existing value. There is no
  guarantee of synchronous operation of calls to setState and calls may
  be batched for performance gains.

If you would like to check if your state is updated, you can either used a callback as the second argument to setState or put some logic in the shouldComponentUpdate(nextProps, nextState) lifecycle method.

Example:

handleChangeDate(date) {
  this.setState({
    dueDate: date
  }, () => console.log(this.state.dueDate)); // This will show the updated state when state is set.
}

or

shouldComponentUpdate(nextProps, nextState) {
  if (this.state.dueDate !== nextState.dueDate) {
    console.log('dueDate:  ', nextState.dueDate);
  }
}

setState Documentation: (Note the function signature, setState(nextState, callback))

https://facebook.github.io/react/docs/react-component.html#setstate

shouldComponentUpdate Documentation:

https://facebook.github.io/react/docs/react-component.html#shouldcomponentupdate


问:
Sorting an object ArrayList by an attribute value in Java
I have ArrayList zombie, which is populated with an object called Zombie. Zombie has the attributes health, x, y. How would I sort the array in ascending order, using the attribute x of Zombie, which is set to initially have random values?

I have already found a possible solution to my problem, but I do not understand the syntax of the answer. Explaining that answer may help, also.

答:
using JAVA 8 do this:

```<code>zombie.sort((Zombie z1, Zombie z2) -> {
   if (z1.x() > z2.x())
     return 1;
   if (z1.x() < z2.x())
     return -1;
   return 0;
});
</code>```

List interface now supports the sort method directly

Body:
using JAVA 8 do this:

zombie.sort((Zombie z1, Zombie z2) -> {
   if (z1.x() > z2.x())
     return 1;
   if (z1.x() < z2.x())
     return -1;
   return 0;
});

List interface now supports the sort method directly


问:
Detect HTML5 Geolocation Support Using PHP
I need to detect HTML5 Geolocation support using PHP so that I can load a backup JavaScript that supports Geolocation using IP Address.

How to do this with or without PHP.

答:
Have you considered using Modernizr to detect the HTML5 support? This isn't PHP specific since it's done in JavaScript but you can use this snippet to load your backup file:

```<code>if (Modernizr.geolocation){
   // Access using HTML5
   navigator.geolocation.getCurrentPosition(function(position) { ... });
}else{
   // Load backup file
   var script = document.createElement('script');
   script.src = '/path/to/your/script.js';
   script.type = 'text/javascript';
   var head = document.getElementsByTagName("head")[0];
   head.appendChild(script);
}
</code>```

(Based on http://www.modernizr.com/docs/#geolocation)

Body:
Have you considered using Modernizr to detect the HTML5 support? This isn't PHP specific since it's done in JavaScript but you can use this snippet to load your backup file:

if (Modernizr.geolocation){
   // Access using HTML5
   navigator.geolocation.getCurrentPosition(function(position) { ... });
}else{
   // Load backup file
   var script = document.createElement('script');
   script.src = '/path/to/your/script.js';
   script.type = 'text/javascript';
   var head = document.getElementsByTagName("head")[0];
   head.appendChild(script);
}

(Based on http://www.modernizr.com/docs/#geolocation)


问:
How to Add an Object Inside Another List Object
I have an object class A, and a list object for class B

```<code>A a = a.findById(aId);
List<B> b = b.findById(bId);
</code>```

Class B has A class

```<code>public class B {
   private int id;
   private A a;
   ...getters setters
}
</code>```

Is it possible to add object a in object list b?

I get error when I try to add a in object list.
b.add(a); This tells me to change object a as B a...

How can I add object a in the list object b?

答:
Is it possible to add object a in object list b?

Simply, no because they're not the same types.

How can I add object a in the list object b?

in order to add both instances of class A and class B into one collection, one approach you can take is to make an interface in which both class A and class B implement.

Example:

```<code>public interface ISomeInterface {
    // define some methods in which both class `A` and `B` share
}
</code>```

Then make the classes implement the ISomeInterface interface:

```<code>public class A implements ISomeInterface {

}

public class B implements ISomeInterface {
    private int id;
    private A a;
}
</code>```

then you can do something like this:

```<code>List<ISomeInterface> b = new ArrayList<>();
b.add(new A());
b.add(new B());
// note you can only call methods through which the interface defines
// another solution is to cast the types, that way you can invoke the methods that belong to each type
// make use of instanceof keyword to prevent exception
</code>```

or simply without the need of making interfaces:

```<code>List<Object> b = new ArrayList<>();
b.add(new A());  //if you want to call the methods of A or B you need to cast it first, remember to use instanceof keyword prior to casting
b.add(new B());
</code>```

Body:
I have an object class A, and a list object for class B

A a = a.findById(aId);
List b = b.findById(bId);

Class B has A class

public class B {
   private int id;
   private A a;
   ...getters setters
}

Is it possible to add object a in object list b?

I get error when I try to add a in object list.
b.add(a); This tells me to change object a as B a...

How can I add object a in the list object b?

Body:
Is it possible to add object a in object list b?

Simply, no because they're not the same types.

How can I add object a in the list object b?

in order to add both instances of class A and class B into one collection, one approach you can take is to make an interface in which both class A and class B implement.

Example:

public interface ISomeInterface {
    // define some methods in which both class `A` and `B` share
}

Then make the classes implement the ISomeInterface interface:

public class A implements ISomeInterface {

}

public class B implements ISomeInterface {
    private int id;
    private A a;
}

then you can do something like this:

List<ISomeInterface> b = new ArrayList<>();
b.add(new A());
b.add(new B());
// note you can only call methods through which the interface defines
// another solution is to cast the types, that way you can invoke the methods that belong to each type
// make use of instanceof keyword to prevent exception

or simply without the need of making interfaces:

List<Object> b = new ArrayList<>();
b.add(new A());  //if you want to call the methods of A or B you need to cast it first, remember to use instanceof keyword prior to casting
b.add(new B());


问:
Copy text from a Windows CMD window to clipboard
Does anyone know if it's possible to copy text from a Windows' command prompt or console window like the output of a command, console application or batch file?</p>

答:
Haloo my friend :

 if you want to copy any text which was currently in the clipboard in
 the Cmd or in the PowerShell you should Just :

1\ Write any command that you want .

2\before pressing enter write |clip and then press Enter .

3\Open any text Editor such as Notepad .

4\ Ctrl+v or Right click -Paste .

and her you have the clipboard in your Text Editor ^_^ .


问:
Error when trying to load a file with sc.textFile in Windows
I am new to hadoop and I am trying to upload a local file using sc.textFile command

```<code>val data = sc.textFile("file:///D:\\test.txt")
</code>```

After this I try to do some operation on this data then I get the error

```<code>java.lang.IllegalArgumentException: java.net.URISyntaxException: Relative path in absolute URI: D:test.txt
        at org.apache.hadoop.fs.Path.initialize(Path.java:206)
        at org.apache.hadoop.fs.Path.<init>(Path.java:172)
        at org.apache.hadoop.fs.Path.<init>(Path.java:94)
        at org.apache.hadoop.fs.Globber.glob(Globber.java:248)
        at org.apache.hadoop.fs.FileSystem.globStatus(FileSystem.java:1698)
        at org.apache.hadoop.mapred.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:229)
        at org.apache.hadoop.mapred.FileInputFormat.listStatus(FileInputFormat.java:200)
        at org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:270)
        at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:179)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:204)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:202)
        at scala.Option.getOrElse(Option.scala:120)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:202)
        at org.apache.spark.rdd.MappedRDD.getPartitions(MappedRDD.scala:28)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:204)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:202)
        at scala.Option.getOrElse(Option.scala:120)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:202)
        at org.apache.spark.rdd.FlatMappedRDD.getPartitions(FlatMappedRDD.scala:30)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:204)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:202)
        at scala.Option.getOrElse(Option.scala:120)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:202)
        at org.apache.spark.rdd.MappedRDD.getPartitions(MappedRDD.scala:28)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:204)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:202)
        at scala.Option.getOrElse(Option.scala:120)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:202)
        at org.apache.spark.Partitioner$.defaultPartitioner(Partitioner.scala:65)
        at org.apache.spark.rdd.PairRDDFunctions.reduceByKey(PairRDDFunctions.scala:279)
        at $iwC$$iwC$$iwC$$iwC.<init>(<console>:16)
        at $iwC$$iwC$$iwC.<init>(<console>:21)
        at $iwC$$iwC.<init>(<console>:23)
        at $iwC.<init>(<console>:25)
        at <init>(<console>:27)
        at .<init>(<console>:31)
        at .<clinit>(<console>)
        at .<init>(<console>:7)
        at .<clinit>(<console>)
        at $print(<console>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.spark.repl.SparkIMain$ReadEvalPrint.call(SparkIMain.scala:789)
        at org.apache.spark.repl.SparkIMain$Request.loadAndRun(SparkIMain.scala:1062)
        at org.apache.spark.repl.SparkIMain.loadAndRunReq$1(SparkIMain.scala:615)
        at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:646)
        at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:610)
        at org.apache.spark.repl.SparkILoop.reallyInterpret$1(SparkILoop.scala:814)
        at org.apache.spark.repl.SparkILoop.interpretStartingWith(SparkILoop.scala:859)
        at org.apache.spark.repl.SparkILoop.command(SparkILoop.scala:771)
        at org.apache.spark.repl.SparkILoop.processLine$1(SparkILoop.scala:616)
        at org.apache.spark.repl.SparkILoop.innerLoop$1(SparkILoop.scala:624)
        at org.apache.spark.repl.SparkILoop.loop(SparkILoop.scala:629)
        at org.apache.spark.repl.SparkILoop$$anonfun$process$1.apply$mcZ$sp(SparkILoop.scala:954)
        at org.apache.spark.repl.SparkILoop$$anonfun$process$1.apply(SparkILoop.scala:902)
        at org.apache.spark.repl.SparkILoop$$anonfun$process$1.apply(SparkILoop.scala:902)
        at scala.tools.nsc.util.ScalaClassLoader$.savingContextLoader(ScalaClassLoader.scala:135)
        at org.apache.spark.repl.SparkILoop.process(SparkILoop.scala:902)
        at org.apache.spark.repl.SparkILoop.process(SparkILoop.scala:997)
        at org.apache.spark.repl.Main$.main(Main.scala:31)
        at org.apache.spark.repl.Main.main(Main.scala)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.spark.deploy.SparkSubmit$.launch(SparkSubmit.scala:328)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:75)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.net.URISyntaxException: Relative path in absolute URI: D:test.txt
        at java.net.URI.checkPath(URI.java:1804)
        at java.net.URI.<init>(URI.java:752)
        at org.apache.hadoop.fs.Path.initialize(Path.java:203)
        ... 69 more
</code>```

I have tried a few variants in the command sc.textFile. Such as

```<code>val data = sc.textFile("file:///D:/test.txt")
</code>```

then I get the error

```<code>java.lang.IllegalArgumentException: java.net.URISyntaxException: Expected scheme-specific part at index 2: D
</code>```

I have been trying for a long time but I am not able to get this basic thing correct. Can someone please help !! Thanks in advance !!

答:
Adding spark.sql.warehouse.dir fixed the problem for me

```<code>System.setProperty("spark.sql.warehouse.dir", "file:///C:/spark-warehouse");
</code>```

Here is the code snippet

```<code>System.setProperty("hadoop.home.dir", "c:/winutil/");
System.setProperty("spark.sql.warehouse.dir", "file:///C:/spark-warehouse");
val conf = new SparkConf().setAppName("test").setMaster("local[*]")
val sc = new SparkContext(conf)
val lines = sc.textFile("C:/user.txt")
</code>```

Body:
I am new to hadoop and I am trying to upload a local file using sc.textFile command

val data = sc.textFile("file:///D:\\test.txt")

After this I try to do some operation on this data then I get the error

java.lang.IllegalArgumentException: java.net.URISyntaxException: Relative path in absolute URI: D:test.txt
        at org.apache.hadoop.fs.Path.initialize(Path.java:206)
        at org.apache.hadoop.fs.Path.<init>(Path.java:172)
        at org.apache.hadoop.fs.Path.<init>(Path.java:94)
        at org.apache.hadoop.fs.Globber.glob(Globber.java:248)
        at org.apache.hadoop.fs.FileSystem.globStatus(FileSystem.java:1698)
        at org.apache.hadoop.mapred.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:229)
        at org.apache.hadoop.mapred.FileInputFormat.listStatus(FileInputFormat.java:200)
        at org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:270)
        at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:179)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:204)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:202)
        at scala.Option.getOrElse(Option.scala:120)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:202)
        at org.apache.spark.rdd.MappedRDD.getPartitions(MappedRDD.scala:28)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:204)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:202)
        at scala.Option.getOrElse(Option.scala:120)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:202)
        at org.apache.spark.rdd.FlatMappedRDD.getPartitions(FlatMappedRDD.scala:30)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:204)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:202)
        at scala.Option.getOrElse(Option.scala:120)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:202)
        at org.apache.spark.rdd.MappedRDD.getPartitions(MappedRDD.scala:28)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:204)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:202)
        at scala.Option.getOrElse(Option.scala:120)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:202)
        at org.apache.spark.Partitioner$.defaultPartitioner(Partitioner.scala:65)
        at org.apache.spark.rdd.PairRDDFunctions.reduceByKey(PairRDDFunctions.scala:279)
        at $iwC$$iwC$$iwC$$iwC.<init>(<console>:16)
        at $iwC$$iwC$$iwC.<init>(<console>:21)
        at $iwC$$iwC.<init>(<console>:23)
        at $iwC.<init>(<console>:25)
        at <init>(<console>:27)
        at .<init>(<console>:31)
        at .<clinit>(<console>)
        at .<init>(<console>:7)
        at .<clinit>(<console>)
        at $print(<console>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.spark.repl.SparkIMain$ReadEvalPrint.call(SparkIMain.scala:789)
        at org.apache.spark.repl.SparkIMain$Request.loadAndRun(SparkIMain.scala:1062)
        at org.apache.spark.repl.SparkIMain.loadAndRunReq$1(SparkIMain.scala:615)
        at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:646)
        at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:610)
        at org.apache.spark.repl.SparkILoop.reallyInterpret$1(SparkILoop.scala:814)
        at org.apache.spark.repl.SparkILoop.interpretStartingWith(SparkILoop.scala:859)
        at org.apache.spark.repl.SparkILoop.command(SparkILoop.scala:771)
        at org.apache.spark.repl.SparkILoop.processLine$1(SparkILoop.scala:616)
        at org.apache.spark.repl.SparkILoop.innerLoop$1(SparkILoop.scala:624)
        at org.apache.spark.repl.SparkILoop.loop(SparkILoop.scala:629)
        at org.apache.spark.repl.SparkILoop$$anonfun$process$1.apply$mcZ$sp(SparkILoop.scala:954)
        at org.apache.spark.repl.SparkILoop$$anonfun$process$1.apply(SparkILoop.scala:902)
        at org.apache.spark.repl.SparkILoop$$anonfun$process$1.apply(SparkILoop.scala:902)
        at scala.tools.nsc.util.ScalaClassLoader$.savingContextLoader(ScalaClassLoader.scala:135)
        at org.apache.spark.repl.SparkILoop.process(SparkILoop.scala:902)
        at org.apache.spark.repl.SparkILoop.process(SparkILoop.scala:997)
        at org.apache.spark.repl.Main$.main(Main.scala:31)
        at org.apache.spark.repl.Main.main(Main.scala)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.spark.deploy.SparkSubmit$.launch(SparkSubmit.scala:328)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:75)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.net.URISyntaxException: Relative path in absolute URI: D:test.txt
        at java.net.URI.checkPath(URI.java:1804)
        at java.net.URI.<init>(URI.java:752)
        at org.apache.hadoop.fs.Path.initialize(Path.java:203)
        ... 69 more

I have tried a few variants in the command sc.textFile. Such as

val data = sc.textFile("file:///D:/test.txt")

then I get the error

java.lang.IllegalArgumentException: java.net.URISyntaxException: Expected scheme-specific part at index 2: D

I have been trying for a long time but I am not able to get this basic thing correct. Can someone please help !! Thanks in advance !!

Body:
Adding spark.sql.warehouse.dir fixed the problem for me

System.setProperty("spark.sql.warehouse.dir", "file:///C:/spark-warehouse");

Here is the code snippet

System.setProperty("hadoop.home.dir", "c:/winutil/");
System.setProperty("spark.sql.warehouse.dir", "file:///C:/spark-warehouse");
val conf = new SparkConf().setAppName("test").setMaster("local[*]")
val sc = new SparkContext(conf)
val lines = sc.textFile("C:/user.txt")


问:
c++ - finding sum and products of elements in array
I'm quite new to c++ and I'm having trouble with this.
It shows the correct sum but the product isn't.

The user specifies how many numbers they'll enter, enters the numbers, the program then prints out the sum and product of all the numbers entered.

What seems to be its problem?

Here's the code:

```<code>#include <iostream>

using namespace std;
int main()
{
int arr[20],i,n,sum=0,product=0;
cout<<"How many elements you want to enter?: ";
cin>>n;

cout << "Please enter " << n << " values to find their sum and product" <<endl;

for(i=0;i<n;i++)
{
cin >> arr[i];
cout << "value #" << i << ": " << arr[i] << " entered." << endl;
}

for(i=0;i<n;i++)
{
sum=sum+arr[i];
}

 for(i=0;i<n;i++)
 {
 product=product*arr[i];
}
cout<<"Sum is "<<sum<<endl;
cout<<"Product is "<<product;

 return 0;
}
</code>```

答: What you have is a simple mathematical error. You declared the product variable to 0, anything multiplied by 0 is equivalent to 0, if you change the value of product to 1, it will solve your issue.

Body:
I'm quite new to c++ and I'm having trouble with this.
It shows the correct sum but the product isn't.

The user specifies how many numbers they'll enter, enters the numbers, the program then prints out the sum and product of all the numbers entered.

What seems to be its problem?

Here's the code:

#include <iostream>

using namespace std;
int main()
{
int arr[20],i,n,sum=0,product=0;
cout<<"How many elements you want to enter?: ";
cin>>n;

cout << "Please enter " << n << " values to find their sum and product" <<endl;

for(i=0;i<n;i++)
{
cin >> arr[i];
cout << "value #" << i << ": " << arr[i] << " entered." << endl;
}

for(i=0;i<n;i++)
{
sum=sum+arr[i];
}

 for(i=0;i<n;i++)
 {
 product=product*arr[i];
}
cout<<"Sum is "<<sum<<endl;
cout<<"Product is "<<product;

 return 0;
}


问:
Additional values in 2d array
I created the following code in Java (1.8.0.121) for parsing of iMatrix array into matrixOutput one.
Once I run it I noticed that appears additional values in cells 1,0 and 1,1.

Could someone advice me how should I change to avoid such additions for other arrays (I plan a generic code which will take different arrays in format like iMatrix array)

    public class Dbg {

```<code>private static int[][] matrixOutput = { { 0, 2, 0, 0, 0 },
                                        { 0, 0, 0, 4, 0 },
                                        { 1, 2, 0, 0, 5 },
                                        { 0, 0, 0, 0, 0 },
                                        { 0, 0, 0, 0, 0 } };
private static int[][] iMatrix = {
        {1, -1, 0, 0, 0},
        {0, 1, 0, -1, 0},
        {-1, 0, 1, 0, 0},
        {0, -1, 1, 0, 0},
        {0, 0, 1, 0, -1},
        {0, 0, 0, 2, 0}};
private static int i = 0;
private static int j = 0;
private static int val = 0;

public static void main(String[] args) {

    int[][] list = new int[5][5];

    for (int m = 0; m < iMatrix.length; m++) {
        for (int n = 0; n < iMatrix[m].length; n++) {
            if (iMatrix[m][n] == 1){
                i = n;
            }
            if (iMatrix[m][n] == -1){
                j = n;
                val = n + 1;

            }
            list[i][j] = val;
        }
    }

    for (i = 0; i < list.length; i++) {
        for (j = 0; j < list.length; j++) {
            System.out.print(list[i][j]);
        }
        System.out.println();
    }

}
}
</code>```

Insead of MatrixOutput it gives me the following result:

```<code>02000
12040
12005
00000
00000
</code>```

When I changed places for 3 and 4 rows viceverso I saw that value 1 from 1,0 disappears. All values from iMatrix are stored correctly.

答:
Rewrote my code with adding a validation for printing and a variable flag.

```<code>private static int[][] iMatrix = {
        {1, -1, 0, 0, 0},
        {0, 1, 0, -1, 0},
        {-1, 0, 1, 0, 0},
        {0, -1, 1, 0, 0},
        {0, 0, 1, 0, -1},
        {0, 0, 0, 2, 0}};
private static int i = 0;
private static int j = 0;
private static int val = 0;
private static int flag = 0;

public static void main(String[] args) {

    int[][] list = new int[5][5];

    for (int m = 0; m < iMatrix.length; m++) {
        for (int n = 0; n < iMatrix[m].length; n++) {
            if (iMatrix[m][n] == 1){
                i = n;
                flag++;
            }
            if (iMatrix[m][n] == -1){
                j = n;
                val = n + 1;
                flag++;
            }

            if (flag == 2){
                list[i][j] = val;
                flag = 0;
            }

        }
    }

    for (i = 0; i < list.length; i++) {
        for (j = 0; j < list.length; j++) {
            System.out.print(list[i][j]);
        }
        System.out.println();
    }

}
</code>```

output became like following:

```<code>02000
00040
12005
00000
00000
</code>```

Title: Additional values in 2d array

Body:
I created the following code in Java (1.8.0.121) for parsing of iMatrix array into matrixOutput one.
Once I run it I noticed that appears additional values in cells 1,0 and 1,1.

Could someone advice me how should I change to avoid such additions for other arrays (I plan a generic code which will take different arrays in format like iMatrix array)

    public class Dbg {

private static int[][] matrixOutput = { { 0, 2, 0, 0, 0 },
                                        { 0, 0, 0, 4, 0 },
                                        { 1, 2, 0, 0, 5 },
                                        { 0, 0, 0, 0, 0 },
                                        { 0, 0, 0, 0, 0 } };
private static int[][] iMatrix = {
        {1, -1, 0, 0, 0},
        {0, 1, 0, -1, 0},
        {-1, 0, 1, 0, 0},
        {0, -1, 1, 0, 0},
        {0, 0, 1, 0, -1},
        {0, 0, 0, 2, 0}};
private static int i = 0;
private static int j = 0;
private static int val = 0;

public static void main(String[] args) {

    int[][] list = new int[5][5];

    for (int m = 0; m < iMatrix.length; m++) {
        for (int n = 0; n < iMatrix[m].length; n++) {
            if (iMatrix[m][n] == 1){
                i = n;
            }
            if (iMatrix[m][n] == -1){
                j = n;
                val = n + 1;

            }
            list[i][j] = val;
        }
    }

    for (i = 0; i < list.length; i++) {
        for (j = 0; j < list.length; j++) {
            System.out.print(list[i][j]);
        }
        System.out.println();
    }

}
}

Insead of MatrixOutput it gives me the following result:

02000
12040
12005
00000
00000

When I changed places for 3 and 4 rows viceverso I saw that value 1 from 1,0 disappears. All values from iMatrix are stored correctly.

Body:
Rewrote my code with adding a validation for printing and a variable flag.

private static int[][] iMatrix = {
        {1, -1, 0, 0, 0},
        {0, 1, 0, -1, 0},
        {-1, 0, 1, 0, 0},
        {0, -1, 1, 0, 0},
        {0, 0, 1, 0, -1},
        {0, 0, 0, 2, 0}};
private static int i = 0;
private static int j = 0;
private static int val = 0;
private static int flag = 0;

public static void main(String[] args) {

    int[][] list = new int[5][5];

    for (int m = 0; m < iMatrix.length; m++) {
        for (int n = 0; n < iMatrix[m].length; n++) {
            if (iMatrix[m][n] == 1){
                i = n;
                flag++;
            }
            if (iMatrix[m][n] == -1){
                j = n;
                val = n + 1;
                flag++;
            }

            if (flag == 2){
                list[i][j] = val;
                flag = 0;
            }

        }
    }

    for (i = 0; i < list.length; i++) {
        for (j = 0; j < list.length; j++) {
            System.out.print(list[i][j]);
        }
        System.out.println();
    }

}

output became like following:

02000
00040
12005
00000
00000


问:
Passing Data Source Connection value through URL in Cognos 10.x
I have a data source with multiple connections.I need to pass Data source connection as a parameter in the URL to select the connection at run time. Currently I get a prompt page for choosing the connection value. I don't want the prompt page to appear, Instead it should take the connection value from URL and continue running the report.
My current connection format as below.

```<code>http://cognos.server/cognos/cgi-bin/cognos.cgi?b_action=cognosViewer&
ui.action=run&ui.object=ui_object&p_credential:dataSourcename:password=<credential><dataSourceConnection>CAMID(":")/dataSource[@name='datasourcename']/dataSourceConnection[@name='datasourceconnectionname']</dataSourceConnection><dataSourceSignon/><username>xxxx</username><password>yyy</password></credential>&run.outputFormat=&run.prompt=false
</code>```

I would appreciate if any help on this?

答:
You are on the right track.. you just need to encode your  <, >, ", [, ], and '.

```<code>http://cognos.server/cognos/cgi-bin/cognos.cgi?b_action=cognosViewer&ui.action=run&ui.object=ui_object&run.outputFormat=&run.prompt=false&p_credential:dataSourcename:password=%3Ccredential%3E%3CdataSourceConnection%3ECAMID(%22:%22)/dataSource%5B@name=%27datasourcename%27%5D/dataSourceConnection%5B@name=%27datasourceconnectionname%27%5D%3C/dataSourceConnection%3E%3CdataSourceSignon/%3E%3Cusername%3Exxxx%3C/username%3E%3Cpassword%3Eyyy%3C/password%3E%3C/credential%3E
</code>```

or with variables

```<code>http://cognos.server/cognos/cgi-bin/cognos.cgi?b_action=cognosViewer&ui.action=run&ui.object=ui_object&run.outputFormat=&run.prompt=false&p_credential:" + dataSourcename + ":password=%3Ccredential%3E%3CdataSourceConnection%3ECAMID(%22:%22)/dataSource%5B@name=%27" + datasourcename + "%27%5D/dataSourceConnection%5B@name=%27" + datasourceconnectionname + "%27%5D%3C/dataSourceConnection%3E%3CdataSourceSignon/%3E%3Cusername%3E" + username + "%3C/username%3E%3Cpassword%3E" + password +"%3C/password%3E%3C/credential%3E
</code>```

Body:
I have a data source with multiple connections.I need to pass Data source connection as a parameter in the URL to select the connection at run time. Currently I get a prompt page for choosing the connection value. I don't want the prompt page to appear, Instead it should take the connection value from URL and continue running the report.
My current connection format as below.

http://cognos.server/cognos/cgi-bin/cognos.cgi?b_action=cognosViewer&
ui.action=run&ui.object=ui_object&p_credential:dataSourcename:password=<credential><dataSourceConnection>CAMID(":")/dataSource[@name='datasourcename']/dataSourceConnection[@name='datasourceconnectionname']</dataSourceConnection><dataSourceSignon/><username>xxxx</username><password>yyy</password></credential>&run.outputFormat=&run.prompt=false

I would appreciate if any help on this?

Body:
You are on the right track.. you just need to encode your  <, >, ", [, ], and '.

http://cognos.server/cognos/cgi-bin/cognos.cgi?b_action=cognosViewer&ui.action=run&ui.object=ui_object&run.outputFormat=&run.prompt=false&p_credential:dataSourcename:password=%3Ccredential%3E%3CdataSourceConnection%3ECAMID(%22:%22)/dataSource%5B@name=%27datasourcename%27%5D/dataSourceConnection%5B@name=%27datasourceconnectionname%27%5D%3C/dataSourceConnection%3E%3CdataSourceSignon/%3E%3Cusername%3Exxxx%3C/username%3E%3Cpassword%3Eyyy%3C/password%3E%3C/credential%3E

or with variables

http://cognos.server/cognos/cgi-bin/cognos.cgi?b_action=cognosViewer&ui.action=run&ui.object=ui_object&run.outputFormat=&run.prompt=false&p_credential:" + dataSourcename + ":password=%3Ccredential%3E%3CdataSourceConnection%3ECAMID(%22:%22)/dataSource%5B@name=%27" + datasourcename + "%27%5D/dataSourceConnection%5B@name=%27" + datasourceconnectionname + "%27%5D%3C/dataSourceConnection%3E%3CdataSourceSignon/%3E%3Cusername%3E" + username + "%3C/username%3E%3Cpassword%3E" + password +"%3C/password%3E%3C/credential%3E


答:
The syntax to add a A to B would be first get B, then add A to B, such as

```<code>A a = new A();
B b = new B();

b.add(A);
</code>```

if you wish to add both to the same List<> then they need to implement the same or inherit from the same class, example interface IAB

```<code>List<IAB> list = new ArrayList<>();

list.add(new A());
list.add(new B());
</code>```

given that

```<code>public interface IAB{}
public class A implements IAB{}
public class B implements IAB();
</code>```

note that in this case you can only call the methods that are available on the Interface unless you cast it to the class (but if you mix A and B that might be complicated to handle)

Title: How to Add an Object Inside Another List Object

Body:
The syntax to add a A to B would be first get B, then add A to B, such as

A a = new A();
B b = new B();

b.add(A);

if you wish to add both to the same List<> then they need to implement the same or inherit from the same class, example interface IAB

List<IAB> list = new ArrayList<>();

list.add(new A());
list.add(new B());

given that

public interface IAB{}
public class A implements IAB{}
public class B implements IAB();

note that in this case you can only call the methods that are available on the Interface unless you cast it to the class (but if you mix A and B that might be complicated to handle)


问:
modifying secant method algorithm
my code below uses the secant method to find the root of an analytic function.  The analytic function, f must be specified in the function part of my code.  The code below works well and has no compilation errors.  However, for the problem I want to solve I do not know the analytic function f.

Instead I calculate the function numerically, and its stored as an array.  I want now apply my code to find the roots of this  function. So how can I modify my code such that the input is not an analytic function, instead just an array which I have already calculated?

My working code is below, I assume I just need to modify the last part where I call the function f, I just am unsure how to go about doing this.  Thanks!

```<code>program main
  implicit none
  real :: a = 1.0, b = -1.0
  integer :: m = 8
  interface
  function f(x)
  real, intent(in) :: x
  end function
  end interface

  call secant(f,a,b,m)
  end program main

  subroutine secant(f,a,b,m)
  implicit none
  real, intent(in out) :: a,b
  integer, intent(in) :: m
  real :: fa, fb, temp
  integer :: n
  interface
  function f(x)
  real, intent(in) :: x
  end function f
  end interface

  fa = f(a)
  fb = f(b)
  if (abs(fa) >  abs(fb)) then
     temp = a
     a = b
     b = temp
     temp = fa
     fa = fb
     fb = temp
  end if
  print *,"    n        x(n)         f(x(n))"
  print *," 0 ", a, fa
  print *," 1 ", b, fb
  do n = 2,m
     if (abs(fa) >  abs(fb)) then
        temp = a
        a = b
        b = temp
        temp = fa
        fa = fb
        fb = temp
     end if
     temp = (b - a)/(fb - fa)
       b = a
     fb = fa
     a = a - fa*temp
     fa = f(a)
     print *,n,a,fa
  end do
  end subroutine secant

  real function f(x)
  implicit none
  real, intent(in) :: x
  f = x**5 + x**3 + 3.0 !analytic form of a function, I don't actually have this though, I just have the function stored as an array
  end function f
</code>```

答:
What I wanted to say in my comments are something as below.

You can modify your secant subroutine to take an object of an abstract class (FAZ) which is guaranteed to have a function f. For example, as following.

solver.f90

```<code>!*****************************************************************
MODULE solver
!*****************************************************************
  IMPLICIT NONE
  PRIVATE

  PUBLIC FAZ
  PUBLIC secant

  TYPE, ABSTRACT :: FAZ
   CONTAINS
     PROCEDURE(f),      deferred, pass :: f
  END TYPE FAZ

  ABSTRACT INTERFACE
     FUNCTION f(this, x)
       IMPORT  :: FAZ
       REAL                           :: f
       CLASS(FAZ),         INTENT(IN) :: this
       REAL,               INTENT(IN) :: x
     END FUNCTION f
  END INTERFACE

!=====================================================================
CONTAINS
!=====================================================================

  subroutine secant(oFAZ,a,b,m)
    CLASS(FAZ)         :: oFAZ
    real, intent(in out) :: a,b
    integer, intent(in) :: m
    real :: fa, fb, temp
    integer :: n

    fa = oFAZ%f(a)
    fb = oFAZ%f(b)
    if (abs(fa) >  abs(fb)) then
       temp = a
       a = b
       b = temp
       temp = fa
       fa = fb
       fb = temp
    end if
    print *,"    n        x(n)         f(x(n))"
    print *," 0 ", a, fa
    print *," 1 ", b, fb
    do n = 2,m
       if (abs(fa) >  abs(fb)) then
          temp = a
          a = b
          b = temp
          temp = fa
          fa = fb
          fb = temp
       end if
       temp = (b - a)/(fb - fa)
       b = a
       fb = fa
       a = a - fa*temp
       fa = oFAZ%f(a)
       print *,n,a,fa
    end do
  end subroutine secant

END MODULE solver
</code>```

You can then implement the behavior of the function f in whatever way you like by extending the abstract class FAZ to a concrete class MyFAZ. For example, I wrote it as following.

myfaz.f90

```<code>!*******************************************************************
MODULE my_concrete_faz
!*******************************************************************
  USE solver, ONLY : FAZ
  IMPLICIT NONE
  PRIVATE

  PUBLIC MyFAZ
  PUBLIC MyFAZ_constructor

  TYPE, EXTENDS(FAZ) :: MyFAZ
     PRIVATE
     REAL,     DIMENSION(:),   ALLOCATABLE :: xdata, fdata
   CONTAINS
     PROCEDURE :: destructor
     PROCEDURE :: f
  END TYPE MyFAZ

! ================================================================
CONTAINS
! ================================================================

  ! ****************************************************************
  FUNCTION MyFAZ_constructor(xdata_arg, fdata_arg) RESULT(oMyFAZ)
  ! ****************************************************************
    TYPE(MyFAZ)                         :: oMyFAZ
    REAL,     DIMENSION(:), INTENT(IN)  :: xdata_arg, fdata_arg
    INTEGER :: ndata, jj

    ndata = size(xdata_arg)
    if (size(fdata_arg) /= ndata) then
       stop 'MyFAZ_constructor: array size mismatch .. ndata'
    end if
    do jj=1,ndata-1
       if (xdata_arg(jj)>xdata_arg(jj+1)) then
          stop 'MyFAZ_constructor: expecting a sorted xdata. I am lazy.'
       end if
    end do
    allocate(oMyFAZ%xdata(ndata))
    allocate(oMyFAZ%fdata(ndata))
    oMyFAZ%xdata = xdata_arg
    oMyFAZ%fdata = fdata_arg

  END FUNCTION MyFAZ_constructor

  ! ****************************************************************
  SUBROUTINE destructor(this)
  ! ****************************************************************
    CLASS(MyFAZ),           INTENT(INOUT) :: this

    deallocate(this%xdata)
    deallocate(this%fdata)

  END SUBROUTINE destructor

  ! ****************************************************************
  FUNCTION f(this, x)
  ! ****************************************************************
    ! evaluates the function.
    ! Linear interpolation is used here, but this will not make sense
    ! in actual application. Everything is written in a very inefficient way.
    REAL                         :: f
    CLASS(MyFAZ),     INTENT(IN) :: this
    REAL,             INTENT(IN) :: x
    !
    INTEGER  :: jj
    REAL     :: rr

    do jj=1, size(this%xdata)-1
       if (this%xdata(jj)<=x .and. x<=this%xdata(jj+1)) then
          exit
       end if
    end do

    rr = (this%fdata(jj+1) - this%fdata(jj))/(this%xdata(jj+1) - this%xdata(jj))
    f  = rr*(x - this%xdata(jj)) + this%fdata(jj)

  END FUNCTION f

END MODULE my_concrete_faz
</code>```

I used the linear interpolation, just for demonstration. Actually, if f(x) = r x + s, then you know the solution without using the secant method.

You will have your own appropriate method to evaluate f(x) between data points.

You can use the above two modules as following.

main.f90

```<code>PROGRAM demo
  USE solver, ONLY : secant
  USE my_concrete_faz, ONLY : MyFAZ, MyFAZ_constructor
  IMPLICIT NONE

  REAL,  DIMENSION(:), ALLOCATABLE :: xdata, fdata
  INTEGER                          :: ndata
  INTEGER                          :: niter_max
  REAL                             :: xa, xb
  TYPE(MyFAZ)                      :: oMyFAZ

  niter_max = 10
  xa = -2.0
  xb =  3.0

  ! prepare data
  ndata = 4
  allocate(xdata(ndata))
  allocate(fdata(ndata))

  xdata(1) = -3.0
  xdata(2) = -1.1
  xdata(3) =  1.2
  xdata(4) =  3.8

  fdata(1) = -1.5
  fdata(2) = -0.9
  fdata(3) =  0.1
  fdata(4) =  0.8

  ! prepare the function
  oMyFAZ = MyFAZ_constructor(xdata, fdata)
  deallocate(xdata)
  deallocate(fdata)

  ! solve
  call secant(oMyFAZ,xa,xb,niter_max)

  write(*,*) '**************'
  write(*,*) 'normal end'
  write(*,*) '**************'

END PROGRAM demo
</code>```

I compiled, built, and got output as following.

```<code>$ ifort -c solver.f90
$ ifort -c myfaz.f90
$ ifort -c main.f90
$ ifort -o demo *.o
$ ./demo
     n        x(n)         f(x(n))
  0    3.000000      0.5846154
  1   -2.000000      -1.184211
           2   1.347448      0.1396975
           3  0.8285716     -6.1490655E-02
           4  0.9871597      7.4606538E-03
           5  0.9700001      0.0000000E+00
           6  0.9700001      0.0000000E+00
           7            NaN            NaN
           8            NaN            NaN
           9            NaN            NaN
          10            NaN            NaN
 **************
 normal end
 **************
$
</code>```

The NaNs are there because your secant subroutine reached to the solution before the maximum iteration, but had no way to exit in the middle of the loop.

Here is a plot of the data.

Title: modifying secant method algorithm

Body:
my code below uses the secant method to find the root of an analytic function.  The analytic function, f must be specified in the function part of my code.  The code below works well and has no compilation errors.  However, for the problem I want to solve I do not know the analytic function f.

Instead I calculate the function numerically, and its stored as an array.  I want now apply my code to find the roots of this  function. So how can I modify my code such that the input is not an analytic function, instead just an array which I have already calculated?

My working code is below, I assume I just need to modify the last part where I call the function f, I just am unsure how to go about doing this.  Thanks!

program main
  implicit none
  real :: a = 1.0, b = -1.0
  integer :: m = 8
  interface
  function f(x)
  real, intent(in) :: x
  end function
  end interface

  call secant(f,a,b,m)
  end program main

  subroutine secant(f,a,b,m)
  implicit none
  real, intent(in out) :: a,b
  integer, intent(in) :: m
  real :: fa, fb, temp
  integer :: n
  interface
  function f(x)
  real, intent(in) :: x
  end function f
  end interface

  fa = f(a)
  fb = f(b)
  if (abs(fa) >  abs(fb)) then
     temp = a
     a = b
     b = temp
     temp = fa
     fa = fb
     fb = temp
  end if
  print *,"    n        x(n)         f(x(n))"
  print *," 0 ", a, fa
  print *," 1 ", b, fb
  do n = 2,m
     if (abs(fa) >  abs(fb)) then
        temp = a
        a = b
        b = temp
        temp = fa
        fa = fb
        fb = temp
     end if
     temp = (b - a)/(fb - fa)
       b = a
     fb = fa
     a = a - fa*temp
     fa = f(a)
     print *,n,a,fa
  end do
  end subroutine secant

  real function f(x)
  implicit none
  real, intent(in) :: x
  f = x**5 + x**3 + 3.0 !analytic form of a function, I don't actually have this though, I just have the function stored as an array
  end function f

Body:
What I wanted to say in my comments are something as below.

You can modify your secant subroutine to take an object of an abstract class (FAZ) which is guaranteed to have a function f. For example, as following.

solver.f90

!*****************************************************************
MODULE solver
!*****************************************************************
  IMPLICIT NONE
  PRIVATE

  PUBLIC FAZ
  PUBLIC secant

  TYPE, ABSTRACT :: FAZ
   CONTAINS
     PROCEDURE(f),      deferred, pass :: f
  END TYPE FAZ

  ABSTRACT INTERFACE
     FUNCTION f(this, x)
       IMPORT  :: FAZ
       REAL                           :: f
       CLASS(FAZ),         INTENT(IN) :: this
       REAL,               INTENT(IN) :: x
     END FUNCTION f
  END INTERFACE

!=====================================================================
CONTAINS
!=====================================================================

  subroutine secant(oFAZ,a,b,m)
    CLASS(FAZ)         :: oFAZ
    real, intent(in out) :: a,b
    integer, intent(in) :: m
    real :: fa, fb, temp
    integer :: n

    fa = oFAZ%f(a)
    fb = oFAZ%f(b)
    if (abs(fa) >  abs(fb)) then
       temp = a
       a = b
       b = temp
       temp = fa
       fa = fb
       fb = temp
    end if
    print *,"    n        x(n)         f(x(n))"
    print *," 0 ", a, fa
    print *," 1 ", b, fb
    do n = 2,m
       if (abs(fa) >  abs(fb)) then
          temp = a
          a = b
          b = temp
          temp = fa
          fa = fb
          fb = temp
       end if
       temp = (b - a)/(fb - fa)
       b = a
       fb = fa
       a = a - fa*temp
       fa = oFAZ%f(a)
       print *,n,a,fa
    end do
  end subroutine secant

END MODULE solver

You can then implement the behavior of the function f in whatever way you like by extending the abstract class FAZ to a concrete class MyFAZ. For example, I wrote it as following.

myfaz.f90

!*******************************************************************
MODULE my_concrete_faz
!*******************************************************************
  USE solver, ONLY : FAZ
  IMPLICIT NONE
  PRIVATE

  PUBLIC MyFAZ
  PUBLIC MyFAZ_constructor

  TYPE, EXTENDS(FAZ) :: MyFAZ
     PRIVATE
     REAL,     DIMENSION(:),   ALLOCATABLE :: xdata, fdata
   CONTAINS
     PROCEDURE :: destructor
     PROCEDURE :: f
  END TYPE MyFAZ

! ================================================================
CONTAINS
! ================================================================

  ! ****************************************************************
  FUNCTION MyFAZ_constructor(xdata_arg, fdata_arg) RESULT(oMyFAZ)
  ! ****************************************************************
    TYPE(MyFAZ)                         :: oMyFAZ
    REAL,     DIMENSION(:), INTENT(IN)  :: xdata_arg, fdata_arg
    INTEGER :: ndata, jj

    ndata = size(xdata_arg)
    if (size(fdata_arg) /= ndata) then
       stop 'MyFAZ_constructor: array size mismatch .. ndata'
    end if
    do jj=1,ndata-1
       if (xdata_arg(jj)>xdata_arg(jj+1)) then
          stop 'MyFAZ_constructor: expecting a sorted xdata. I am lazy.'
       end if
    end do
    allocate(oMyFAZ%xdata(ndata))
    allocate(oMyFAZ%fdata(ndata))
    oMyFAZ%xdata = xdata_arg
    oMyFAZ%fdata = fdata_arg

  END FUNCTION MyFAZ_constructor

  ! ****************************************************************
  SUBROUTINE destructor(this)
  ! ****************************************************************
    CLASS(MyFAZ),           INTENT(INOUT) :: this

    deallocate(this%xdata)
    deallocate(this%fdata)

  END SUBROUTINE destructor

  ! ****************************************************************
  FUNCTION f(this, x)
  ! ****************************************************************
    ! evaluates the function.
    ! Linear interpolation is used here, but this will not make sense
    ! in actual application. Everything is written in a very inefficient way.
    REAL                         :: f
    CLASS(MyFAZ),     INTENT(IN) :: this
    REAL,             INTENT(IN) :: x
    !
    INTEGER  :: jj
    REAL     :: rr

    do jj=1, size(this%xdata)-1
       if (this%xdata(jj)<=x .and. x<=this%xdata(jj+1)) then
          exit
       end if
    end do

    rr = (this%fdata(jj+1) - this%fdata(jj))/(this%xdata(jj+1) - this%xdata(jj))
    f  = rr*(x - this%xdata(jj)) + this%fdata(jj)

  END FUNCTION f

END MODULE my_concrete_faz

I used the linear interpolation, just for demonstration. Actually, if f(x) = r x + s, then you know the solution without using the secant method.

You will have your own appropriate method to evaluate f(x) between data points.

You can use the above two modules as following.

main.f90

PROGRAM demo
  USE solver, ONLY : secant
  USE my_concrete_faz, ONLY : MyFAZ, MyFAZ_constructor
  IMPLICIT NONE

  REAL,  DIMENSION(:), ALLOCATABLE :: xdata, fdata
  INTEGER                          :: ndata
  INTEGER                          :: niter_max
  REAL                             :: xa, xb
  TYPE(MyFAZ)                      :: oMyFAZ

  niter_max = 10
  xa = -2.0
  xb =  3.0

  ! prepare data
  ndata = 4
  allocate(xdata(ndata))
  allocate(fdata(ndata))

  xdata(1) = -3.0
  xdata(2) = -1.1
  xdata(3) =  1.2
  xdata(4) =  3.8

  fdata(1) = -1.5
  fdata(2) = -0.9
  fdata(3) =  0.1
  fdata(4) =  0.8

  ! prepare the function
  oMyFAZ = MyFAZ_constructor(xdata, fdata)
  deallocate(xdata)
  deallocate(fdata)

  ! solve
  call secant(oMyFAZ,xa,xb,niter_max)

  write(*,*) '**************'
  write(*,*) 'normal end'
  write(*,*) '**************'

END PROGRAM demo

I compiled, built, and got output as following.

$ ifort -c solver.f90
$ ifort -c myfaz.f90
$ ifort -c main.f90
$ ifort -o demo *.o
$ ./demo
     n        x(n)         f(x(n))
  0    3.000000      0.5846154
  1   -2.000000      -1.184211
           2   1.347448      0.1396975
           3  0.8285716     -6.1490655E-02
           4  0.9871597      7.4606538E-03
           5  0.9700001      0.0000000E+00
           6  0.9700001      0.0000000E+00
           7            NaN            NaN
           8            NaN            NaN
           9            NaN            NaN
          10            NaN            NaN
 **************
 normal end
 **************
$

The NaNs are there because your secant subroutine reached to the solution before the maximum iteration, but had no way to exit in the middle of the loop.

Here is a plot of the data.