问:
Toggle multiple divs with classes
I need some help:

```<code>    <button">Text</button>
<div class="show-on-button-click">Content</div>

<button">Text2</button>
<div class="show-on-button-click">Content2</div>

<button">Text3</button>
<div class="show-on-button-click">Content3</div>
</code>```

I´de like to show content when the user clicks on the button. But it wont work, even all divs are shown, or it doesnt open and only the buttons are shown.

THX

答:
You have to use some JavaScript/Jquery ;-

```<code>$(document).ready(function(){

    $("button").click(function(){
        $(".show-on-button-click").toggle();
    });
});
</code>```

Hope you solve it !!

Title: Toggle multiple divs with classes

Body:
I need some help:

    <button">Text</button>

Content

<button">Text2</button>

Content2

<button">Text3</button>

Content3

I´de like to show content when the user clicks on the button. But it wont work, even all divs are shown, or it doesnt open and only the buttons are shown.

THX

Body:
You have to use some JavaScript/Jquery ;-

$(document).ready(function(){

    $("button").click(function(){
        $(".show-on-button-click").toggle();
    });
});

Hope you solve it !!


来源: stackexchange

问:
Can only get my data scraper to pull data from one listing, whenever i build a for loop it gives an error
I am trying to pull data of all the sold listings on Ebay for a particular item. I figured out how to grab the first item on the page but when I try to make a for loop to grab all the subsequent posts, it fails

```<code>from bs4 import BeautifulSoup
import requests

source = requests.get('https://www.ebay.com/sch/i.html?_from=R40&_sacat=0&_nkw=charmander%201st%20edition%20psa%2010&LH_Complete=1&LH_Sold=1&rt=nc&_trksid=p2045573.m1684').text

soup = BeautifulSoup(source, 'lxml').find('w-root')
#This gives the HTML of the page that includes all the listings

item = soup.li
#each specific item is in an li tag and this variable grabs the first item that was sold

title = item.h3.a.text

print(title)

price = item.span.text

print(price)

#correctly prints out the Title and price of the first listing
</code>```

that part works fine, its just when i try and do a for loop to grab all the other listings I get an error.

I've tried a few different things but here is an example:

```<code>for li in soup:

    title = li

    print(title)

#this gives me the tags for each listing but when i try and go deeper into the tags like...

for li in soup:

    title = li.h3.a.text  #similar to how i originally grabbed the first item

    print(title)

it prints out: "AttributeError: 'NavigableString' object has no attribute 'h3'"
</code>```

and similarly for the price variable. I cant even do li.prettify() without getting this error.

If i am using a bad approach or anyone knows how to fix this i would greatly appreciate it. Thanks

答:
Try this code, your getting this error because not all li will have  tag encapsulated within a
 tag

```<code>for li in soup:
    try:
        title = li.h3.a.text
    except:
        continue
    print(title)
</code>```

 EDIT

Using find_all() can be used to get all items and its prices.You can loop through items and prices. I already tried to print the first 5 items, as you can see

```<code>items= soup.find_all('h3',class_='lvtitle')
price= soup.find_all('li',class_='lvprice prc')
for i in range(5):
    print items[i].text,price[i].text
</code>```

 Output

1st Edition Pokemon Psa 10 Charmander Base Set Shadowless 46/102, New Case!
  $95.00

Pokemon 1st Edition Base Set CHARMANDER Shadowless #46 PSA 10 GEM Mint
  $111.00

Pokemon 1st Edition Base Set CHARMANDER Shadowless #46 PSA 10 GEM Mint
  $114.95 Was: Previous Price $121.00

Pokemon PSA 10 GEM MINT 1st Edition Shadowless Charmander - English Base Set
  $119.99

Pokemon PSA 10 - Charizard, Charmeleon, + Charmander - POKEKYUN 1st Edition $60.00

ContentLicense: CC BY-SA 3.0

Body:
I am trying to pull data of all the sold listings on Ebay for a particular item. I figured out how to grab the first item on the page but when I try to make a for loop to grab all the subsequent posts, it fails

from bs4 import BeautifulSoup
import requests

source = requests.get('https://www.ebay.com/sch/i.html?_from=R40&_sacat=0&_nkw=charmander%201st%20edition%20psa%2010&LH_Complete=1&LH_Sold=1&rt=nc&_trksid=p2045573.m1684').text

soup = BeautifulSoup(source, 'lxml').find('w-root')
#This gives the HTML of the page that includes all the listings

item = soup.li
#each specific item is in an li tag and this variable grabs the first item that was sold

title = item.h3.a.text

print(title)

price = item.span.text

print(price)

#correctly prints out the Title and price of the first listing

that part works fine, its just when i try and do a for loop to grab all the other listings I get an error.

I've tried a few different things but here is an example:

for li in soup:

    title = li

    print(title)

#this gives me the tags for each listing but when i try and go deeper into the tags like...

for li in soup:

    title = li.h3.a.text  #similar to how i originally grabbed the first item

    print(title)

it prints out: "AttributeError: 'NavigableString' object has no attribute 'h3'"

and similarly for the price variable. I cant even do li.prettify() without getting this error.

If i am using a bad approach or anyone knows how to fix this i would greatly appreciate it. Thanks

Body:
Try this code, your getting this error because not all li will have <a> tag encapsulated within a <h3> tag

for li in soup:
    try:
        title = li.h3.a.text
    except:
        continue
    print(title)

 EDIT

Using find_all() can be used to get all items and its prices.You can loop through items and prices. I already tried to print the first 5 items, as you can see

items= soup.find_all('h3',class_='lvtitle')
price= soup.find_all('li',class_='lvprice prc')
for i in range(5):
    print items[i].text,price[i].text

 Output

1st Edition Pokemon Psa 10 Charmander Base Set Shadowless 46/102, New Case!
  $95.00

Pokemon 1st Edition Base Set CHARMANDER Shadowless #46 PSA 10 GEM Mint
  $111.00

Pokemon 1st Edition Base Set CHARMANDER Shadowless #46 PSA 10 GEM Mint
  $114.95 Was: Previous Price $121.00

Pokemon PSA 10 GEM MINT 1st Edition Shadowless Charmander - English Base Set
  $119.99

Pokemon PSA 10 - Charizard, Charmeleon, + Charmander - POKEKYUN 1st Edition $60.00


问:
Django custom decorator - function has no attribute get
I'm trying to create my own decorator based on @cache_page decorator. My decorator should work exactly like @cache_page except when slug attribute of the view matches request.user.userprofile slug, then normally process the view and return not cached response

Pseudocode:

```<code>def profile(request,slug):
    # if not request.user = User.objects.get(userprofile__slug=slug):
    # return cache
    # else compute response and return it
</code>```

My decorator:

```<code>def exclude_cache_for_request_user(*args, **kwargs):
    def exclude_cache_for_request_user_decorator(func):
        def func_wrapper(*fargs,**fkwargs):
            request = fargs[0]
            if request:
                user = getattr(request,'user',None)
                owner_slug = fkwargs.get('slug')
                owner = User.objects.get(userprofile__slug=owner_slug)
                if user==owner:
                    return func(*fargs, **fkwargs)
                else:
                    if len(args) != 1 or callable(args[0]):
                        raise TypeError("cache_page has a single mandatory positional argument: timeout")
                    cache_timeout = args[0]
                    cache_alias = kwargs.pop('cache', None)
                    key_prefix = kwargs.pop('key_prefix', None)
                    if kwargs:
                        raise TypeError("cache_page has two optional keyword arguments: cache and key_prefix")

                    return decorator_from_middleware_with_args(CacheMiddleware)(
                        cache_timeout=cache_timeout, cache_alias=cache_alias, key_prefix=key_prefix
                    )
        return func_wrapper
    return exclude_cache_for_request_user_decorator
</code>```

This works if user matches the slug. Otherwise, it raises:

Exception Value:

  'function' object has no attribute 'get'

Full traceback:

```<code>File "/home/milano/.virtualenvs/beduenovenv/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/home/milano/.virtualenvs/beduenovenv/local/lib/python2.7/site-packages/django/utils/deprecation.py" in __call__
  142.             response = self.process_response(request, response)

File "/home/milano/.virtualenvs/beduenovenv/local/lib/python2.7/site-packages/django/middleware/clickjacking.py" in process_response
  32.         if response.get('X-Frame-Options') is not None:

Exception Type: AttributeError at /profiles/detail/cingo/
Exception Value: 'function' object has no attribute 'get'
</code>```

Do you know where is the problem? The best would be if there were caching for user and other users separately. So 2 caches for this view.

EDIT: This is an original @cache_page decorator

```<code>def cache_page(*args, **kwargs):
    """
    Decorator for views that tries getting the page from the cache and
    populates the cache if the page isn't in the cache yet.

    The cache is keyed by the URL and some data from the headers.
    Additionally there is the key prefix that is used to distinguish different
    cache areas in a multi-site setup. You could use the
    get_current_site().domain, for example, as that is unique across a Django
    project.

    Additionally, all headers from the response's Vary header will be taken
    into account on caching -- just like the middleware does.
    """
    # We also add some asserts to give better error messages in case people are
    # using other ways to call cache_page that no longer work.
    if len(args) != 1 or callable(args[0]):
        raise TypeError("cache_page has a single mandatory positional argument: timeout")
    cache_timeout = args[0]
    cache_alias = kwargs.pop('cache', None)
    key_prefix = kwargs.pop('key_prefix', None)
    if kwargs:
        raise TypeError("cache_page has two optional keyword arguments: cache and key_prefix")

    return decorator_from_middleware_with_args(CacheMiddleware)(
        cache_timeout=cache_timeout, cache_alias=cache_alias, key_prefix=key_prefix
    )
</code>```

答:
You're returning yet another decorator in the else clause. But at that point you need to be actually calling the decorated function and returning its result, as you do in the if clause.

(Note, the original decorator you post only has a single level of function and returns the decorator from that level, not from inside as you are trying to do.)

Edit You need to do the action of that decorator here: that is, check the cache, and either return the cached item or call the view.

To be honest, the easiest thing is to simply write that functionality directly. Stripped of all the logic the decorator and middleware do to make them generic, it's just:

```<code>key = get_cache_key(request, key_prefix=key_prefix, 'GET', cache=cache_alias)
response = cache.get(cache_key)
if response is None:
    response = func(*fargs, **fkwargs)
    cache.set(cache_key, response, cache_timeout)
return response
</code>```

Body:
I'm trying to create my own decorator based on @cache_page decorator. My decorator should work exactly like @cache_page except when slug attribute of the view matches request.user.userprofile slug, then normally process the view and return not cached response

Pseudocode:

def profile(request,slug):
    # if not request.user = User.objects.get(userprofile__slug=slug):
    # return cache
    # else compute response and return it

My decorator:

def exclude_cache_for_request_user(*args, **kwargs):
    def exclude_cache_for_request_user_decorator(func):
        def func_wrapper(*fargs,**fkwargs):
            request = fargs[0]
            if request:
                user = getattr(request,'user',None)
                owner_slug = fkwargs.get('slug')
                owner = User.objects.get(userprofile__slug=owner_slug)
                if user==owner:
                    return func(*fargs, **fkwargs)
                else:
                    if len(args) != 1 or callable(args[0]):
                        raise TypeError("cache_page has a single mandatory positional argument: timeout")
                    cache_timeout = args[0]
                    cache_alias = kwargs.pop('cache', None)
                    key_prefix = kwargs.pop('key_prefix', None)
                    if kwargs:
                        raise TypeError("cache_page has two optional keyword arguments: cache and key_prefix")

                    return decorator_from_middleware_with_args(CacheMiddleware)(
                        cache_timeout=cache_timeout, cache_alias=cache_alias, key_prefix=key_prefix
                    )
        return func_wrapper
    return exclude_cache_for_request_user_decorator

This works if user matches the slug. Otherwise, it raises:

Exception Value:

  'function' object has no attribute 'get'

Full traceback:

File "/home/milano/.virtualenvs/beduenovenv/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/home/milano/.virtualenvs/beduenovenv/local/lib/python2.7/site-packages/django/utils/deprecation.py" in __call__
  142.             response = self.process_response(request, response)

File "/home/milano/.virtualenvs/beduenovenv/local/lib/python2.7/site-packages/django/middleware/clickjacking.py" in process_response
  32.         if response.get('X-Frame-Options') is not None:

Exception Type: AttributeError at /profiles/detail/cingo/
Exception Value: 'function' object has no attribute 'get'

Do you know where is the problem? The best would be if there were caching for user and other users separately. So 2 caches for this view.

EDIT: This is an original @cache_page decorator

def cache_page(*args, **kwargs):
    """
    Decorator for views that tries getting the page from the cache and
    populates the cache if the page isn't in the cache yet.

    The cache is keyed by the URL and some data from the headers.
    Additionally there is the key prefix that is used to distinguish different
    cache areas in a multi-site setup. You could use the
    get_current_site().domain, for example, as that is unique across a Django
    project.

    Additionally, all headers from the response's Vary header will be taken
    into account on caching -- just like the middleware does.
    """
    # We also add some asserts to give better error messages in case people are
    # using other ways to call cache_page that no longer work.
    if len(args) != 1 or callable(args[0]):
        raise TypeError("cache_page has a single mandatory positional argument: timeout")
    cache_timeout = args[0]
    cache_alias = kwargs.pop('cache', None)
    key_prefix = kwargs.pop('key_prefix', None)
    if kwargs:
        raise TypeError("cache_page has two optional keyword arguments: cache and key_prefix")

    return decorator_from_middleware_with_args(CacheMiddleware)(
        cache_timeout=cache_timeout, cache_alias=cache_alias, key_prefix=key_prefix
    )

Body:
You're returning yet another decorator in the else clause. But at that point you need to be actually calling the decorated function and returning its result, as you do in the if clause.

(Note, the original decorator you post only has a single level of function and returns the decorator from that level, not from inside as you are trying to do.)

Edit You need to do the action of that decorator here: that is, check the cache, and either return the cached item or call the view.

To be honest, the easiest thing is to simply write that functionality directly. Stripped of all the logic the decorator and middleware do to make them generic, it's just:

key = get_cache_key(request, key_prefix=key_prefix, 'GET', cache=cache_alias)
response = cache.get(cache_key)
if response is None:
    response = func(*fargs, **fkwargs)
    cache.set(cache_key, response, cache_timeout)
return response


问:
Query including sum from two tables and join them
I have two tables:

Invoice

```<code>id | name | invoice_number | invoice_total
</code>```

Balancesheet

```<code>id | name | invoice_number | amount_received | discount
</code>```

I want an SQL query to join them grouped by name, and want to sum of invoice_total from the invoice table, and sum of amount_received and sum of discount for individual name from balancesheet table.

Result should be:

```<code>    name | sum(invoice_total) | sum(amount_received) | sum(discount)
</code>```

Any help would be greatly appreciated.

答:
Try</p>

```<code>SELECT
    `NAME`,
    SUM(`INVOICE_TOTAL`) AS invTotal,
    SUM(`AMOUNT_RECEIVED`) AS amtRxd,
    SUM(`DISCOUNT`) AS totalDiscount
    FROM `TABLE-1` T1
        LEFT JOIN `TABLE-2` T2
            ON T1.NAME=T2.NAME
    GROUP BY T1.NAME
</code>```

Body:
I have two tables:

Invoice

id | name | invoice_number | invoice_total

Balancesheet

id | name | invoice_number | amount_received | discount

I want an SQL query to join them grouped by name, and want to sum of invoice_total from the invoice table, and sum of amount_received and sum of discount for individual name from balancesheet table.

Result should be:

    name | sum(invoice_total) | sum(amount_received) | sum(discount)

Any help would be greatly appreciated.

Body:
Try

SELECT
    `NAME`,
    SUM(`INVOICE_TOTAL`) AS invTotal,
    SUM(`AMOUNT_RECEIVED`) AS amtRxd,
    SUM(`DISCOUNT`) AS totalDiscount
    FROM `TABLE-1` T1
        LEFT JOIN `TABLE-2` T2
            ON T1.NAME=T2.NAME
    GROUP BY T1.NAME


问:
Can itextsharp.xmlworker render embedded images?
I would like to create dynamic PDF documents using HTML and dynamic images. My code works fine with standard HTML and full paths for the images, but when I try to embed the image inline in the document I get the error

Exception Details: System.IO.IOException: The document has no pages.

Is there a way to embed the images without an HTTP call per image? I don't want that because I think it will cause scalability issues and the images are sensitive.

Here is my code that gives the IOException:

```<code>    public ActionResult MakePdf()
    {
        string html = @"<?xml version=""1.0"" encoding=""UTF-8""?>
             <!DOCTYPE html
                 PUBLIC ""-//W3C//DTD XHTML 1.0 Strict//EN""
                ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"">
             <html xmlns=""http://www.w3.org/1999/xhtml"" xml:lang=""en"" lang=""en"">
                <head>
                    <title>Minimal XHTML 1.0 Document with W3C DTD</title>
                </head>
              <body><img src='data:image/png;base64,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' width='62' height='80' style='float: left; margin-right: 28px;' /></body></html>";

        var bytes = Encoding.UTF8.GetBytes(html);

        using (MemoryStream input = new MemoryStream(bytes))
        {
            MemoryStream output = new MemoryStream();
            using (Document document = new Document(PageSize.LETTER, 50, 50, 50, 50))
            {
                using (PdfWriter writer = PdfWriter.GetInstance(document, output))
                {
                    writer.CloseStream = false;
                    document.Open();

                    XMLWorkerHelper xmlWorker = XMLWorkerHelper.GetInstance();
                    xmlWorker.ParseXHtml(writer, document, input, null);
                    document.Close();
                    output.Position = 0;

                    return new FileStreamResult(output, "application/pdf");
                }
            }
        }
    }
</code>```

答:
```<code>            string originalFile = "Original1.pdf";
            string copyOfOriginal = "Re-copia.pdf";

            byte[] bytes = Convert.FromBase64String(archivo);

            System.IO.FileStream stream = new FileStream(originalFile, FileMode.CreateNew);
            System.IO.BinaryWriter writer = new BinaryWriter(stream);
            writer.Write(bytes, 0, bytes.Length);
            writer.Close();

            PdfReader reader1 = new PdfReader(originalFile);
            using (FileStream fs = new FileStream(copyOfOriginal, FileMode.Create, FileAccess.Write, FileShare.None))
            // Creating iTextSharp.text.pdf.PdfStamper object to write
            // Data from iTextSharp.text.pdf.PdfReader object to FileStream object
            using (PdfStamper stamper = new PdfStamper(reader1, fs))
            {

                int pageCount = reader1.NumberOfPages;

                // Create New Layer for Watermark
                PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer);
                // Loop through each Page
                for (int i = pageCount; i <= pageCount; i++)
                {
                    // Getting the Page Size
                    Rectangle rect = reader1.GetPageSize(i);

                    // Get the ContentByte object
                    PdfContentByte cb = stamper.GetUnderContent(i);

                    // Tell the cb that the next commands should be "bound" to this new layer
                    cb.BeginLayer(layer);
                    cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50);

                    PdfGState gState = new PdfGState();
                    cb.SetGState(gState);

                    string codbartest = codBarras;
                    BarcodePDF417 bcpdf417 = new BarcodePDF417();
                    //Asigna el código de barras en base64 a la propiedad text del objeto..
                    bcpdf417.Text = ASCIIEncoding.ASCII.GetBytes(codbartest);
                    Image imgpdf417 = bcpdf417.GetImage();
                    imgpdf417.SetAbsolutePosition(50, 50);
                    imgpdf417.ScalePercent(100);
                    cb.AddImage(imgpdf417);
                    // Close the layer
                    cb.EndLayer();
                }[enter image description here][1]
</code>```

Body:
I would like to create dynamic PDF documents using HTML and dynamic images. My code works fine with standard HTML and full paths for the images, but when I try to embed the image inline in the document I get the error

Exception Details: System.IO.IOException: The document has no pages.

Is there a way to embed the images without an HTTP call per image? I don't want that because I think it will cause scalability issues and the images are sensitive.

Here is my code that gives the IOException:

    public ActionResult MakePdf()
    {
        string html = @"<?xml version=""1.0"" encoding=""UTF-8""?>
             <!DOCTYPE html
                 PUBLIC ""-//W3C//DTD XHTML 1.0 Strict//EN""
                ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"">

                    <title>Minimal XHTML 1.0 Document with W3C DTD</title>

              <img src='data:image/png;base64,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' width='62' height='80' style='float: left; margin-right: 28px;' />";

        var bytes = Encoding.UTF8.GetBytes(html);

        using (MemoryStream input = new MemoryStream(bytes))
        {
            MemoryStream output = new MemoryStream();
            using (Document document = new Document(PageSize.LETTER, 50, 50, 50, 50))
            {
                using (PdfWriter writer = PdfWriter.GetInstance(document, output))
                {
                    writer.CloseStream = false;
                    document.Open();

                    XMLWorkerHelper xmlWorker = XMLWorkerHelper.GetInstance();
                    xmlWorker.ParseXHtml(writer, document, input, null);
                    document.Close();
                    output.Position = 0;

                    return new FileStreamResult(output, "application/pdf");
                }
            }
        }
    }


问:
Values not being submitted from PHP HTML form
I am trying to take the input from drop down menus that users enter and submit them to a table in my database. I am trying to submit the values into this table:
I use the POST to check that the values are being pulled from the HTML form and they are, but they won't submit into my table. I've made sure that all of the names with the columns and HTML forms are correct, why won't the values post to the table?

```<code><?php

$databaseName = 'pizza_db';
$databaseUser = 'root';
$databasePassword = 'root';
$databaseHost = '127.0.0.1';
$conn = new mysqli($databaseHost, $databaseUser, $databasePassword, $databaseName);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected sucessfully\n";

if(isset($_POST['submit'])){
$value = mysqli_real_escape_string($conn,$_POST['drink']);
$value2 = mysqli_real_escape_string($conn,$_POST['cheese']);
$value3 = mysqli_real_escape_string($conn,$_POST['veggies']);
$value4 = mysqli_real_escape_string($conn,$_POST['meat']);
$value5 = mysqli_real_escape_string($conn,$_POST['sauce']);
$value6 = mysqli_real_escape_string($conn,$_POST['crust']);
$value7 = mysqli_real_escape_string($conn,$_POST['size']);

$sql = "INSERT INTO order_info(drink,cheese,veggies,meat,sauce,crust,size)
    VALUES('$value','$value2','$value3','$value4','$value5','$value6','$value7')";

//Here I am posting the values to check that they are being submitted
echo $_POST["size"];
echo "\n";
echo $_POST["sauce"];
echo "\n";
echo $_POST["crust"];
echo "\n";
echo $_POST["cheese"];
echo "\n";
echo $_POST["meat"];
echo "\n";
echo $_POST["veggies"];
echo "\n";
echo $_POST["drink"];
$conn->close();
}
?>

<!DOCTYPE html>
<html>
<body>
<form action='' method='post'>

<p>Choose a size<p>
<select id="size" name="size">
  <option value="small">Small</option>
  <option value="medium">Medium</option>
  <option value="large">Large</option>
  <option value="x-large">X-large</option>
</select>

<p> Choose a sauce <p>
<select id="sauce" name="sauce">
  <option value="none">None</option>
  <option value="marinara">Marinara</option>
  <option value="alfredo">Alfredo</option>
  <option value="ranch">Ranch</option>
  <option value="bbq">BBQ</option>
</select>

<p> Choose a cheese<p>
<select id="cheese" name="cheese">
  <option value="none">None</option>
  <option value="mozzarelaa">Mozarella</option>
  <option value="cheddar">Cheddar</option>
  <option value="parmesan">Parmesan</option>
  <option value="three cheese">Three-Cheese</option>
</select>

<p> Choose a meat <p>
<select id="meat" name="meat">
  <option value="none">None</option>
  <option value="Pepperroni">Pepperroni</option>
  <option value="sausage">Sausage</option>
  <option value="bacon">Bacon</option>
  <option value="canadian bacon">Canadian Bacon</option>
  <option value="chicken">Chicken</option>
  <option value="salami">Beef</option>
  <option value="anchovies">Anchovies</option>
</select>

<p> Choose a veggies <p>
<select id="veggies" name="veggies">
  <option value="none">None</option>
  <option value="onions">Onions</option>
  <option value="green peppers">Green Peppers</option>
  <option value="Red peppers">Red peppers</option>
  <option value="Black olives">Mushrooms</option>
   <option value="jalapenos">Jalapenos</option>
    <option value="tomatoes">Tomatoes</option>
    <option value="pineapple">Pineapple</option>
</select>

<p> Choose a crust <p>
<select id="crust" name="crust">
  <option value="regular">Regular</option>
  <option value="deep-dish">Deep-dish</option>
  <option value="thin-crust">Thin Crust</option>
  <option value="stuffed crust">Stuffed Crust</option>
  <option value="gluten free">Gluten Free</option>
</select>

<p> Choose a drink <p>
<select id="drink" name="drink">
  <option value="none">None</option>
  <option value="rootbeer">Root Beer</option>
  <option value="coke">Coke</option>
  <option value="diet coke">Diet Coke</option>
  <option value="dr pepper">Dr Pepper</option>
</select>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
</code>```

答:
Seems like you are not running the query.</p>

```<code>// sql
$sql = "INSERT INTO order_info(drink,cheese,veggies,meat,sauce,crust,size)
VALUES('$value','$value2','$value3','$value4','$value5','$value6','$value7')";

// run query
mysqli_query($conn, $sql);

// or
$conn->query($sql);
</code>```

Body:
I am trying to take the input from drop down menus that users enter and submit them to a table in my database. I am trying to submit the values into this table:
I use the POST to check that the values are being pulled from the HTML form and they are, but they won't submit into my table. I've made sure that all of the names with the columns and HTML forms are correct, why won't the values post to the table?

<?php

$databaseName = 'pizza_db';
$databaseUser = 'root';
$databasePassword = 'root';
$databaseHost = '127.0.0.1';
$conn = new mysqli($databaseHost, $databaseUser, $databasePassword, $databaseName);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected sucessfully\n";

if(isset($_POST['submit'])){
$value = mysqli_real_escape_string($conn,$_POST['drink']);
$value2 = mysqli_real_escape_string($conn,$_POST['cheese']);
$value3 = mysqli_real_escape_string($conn,$_POST['veggies']);
$value4 = mysqli_real_escape_string($conn,$_POST['meat']);
$value5 = mysqli_real_escape_string($conn,$_POST['sauce']);
$value6 = mysqli_real_escape_string($conn,$_POST['crust']);
$value7 = mysqli_real_escape_string($conn,$_POST['size']);

$sql = "INSERT INTO order_info(drink,cheese,veggies,meat,sauce,crust,size)
    VALUES('$value','$value2','$value3','$value4','$value5','$value6','$value7')";

//Here I am posting the values to check that they are being submitted
echo $_POST["size"];
echo "\n";
echo $_POST["sauce"];
echo "\n";
echo $_POST["crust"];
echo "\n";
echo $_POST["cheese"];
echo "\n";
echo $_POST["meat"];
echo "\n";
echo $_POST["veggies"];
echo "\n";
echo $_POST["drink"];
$conn->close();
}
?>

<!DOCTYPE html>

<form action='' method='post'>

Choose a size

<select id="size" name="size">
  <option value="small">Small</option>
  <option value="medium">Medium</option>
  <option value="large">Large</option>
  <option value="x-large">X-large</option>
</select>

 Choose a sauce

<select id="sauce" name="sauce">
  <option value="none">None</option>
  <option value="marinara">Marinara</option>
  <option value="alfredo">Alfredo</option>
  <option value="ranch">Ranch</option>
  <option value="bbq">BBQ</option>
</select>

 Choose a cheese

<select id="cheese" name="cheese">
  <option value="none">None</option>
  <option value="mozzarelaa">Mozarella</option>
  <option value="cheddar">Cheddar</option>
  <option value="parmesan">Parmesan</option>
  <option value="three cheese">Three-Cheese</option>
</select>

 Choose a meat

<select id="meat" name="meat">
  <option value="none">None</option>
  <option value="Pepperroni">Pepperroni</option>
  <option value="sausage">Sausage</option>
  <option value="bacon">Bacon</option>
  <option value="canadian bacon">Canadian Bacon</option>
  <option value="chicken">Chicken</option>
  <option value="salami">Beef</option>
  <option value="anchovies">Anchovies</option>
</select>

 Choose a veggies

<select id="veggies" name="veggies">
  <option value="none">None</option>
  <option value="onions">Onions</option>
  <option value="green peppers">Green Peppers</option>
  <option value="Red peppers">Red peppers</option>
  <option value="Black olives">Mushrooms</option>
   <option value="jalapenos">Jalapenos</option>
    <option value="tomatoes">Tomatoes</option>
    <option value="pineapple">Pineapple</option>
</select>

 Choose a crust

<select id="crust" name="crust">
  <option value="regular">Regular</option>
  <option value="deep-dish">Deep-dish</option>
  <option value="thin-crust">Thin Crust</option>
  <option value="stuffed crust">Stuffed Crust</option>
  <option value="gluten free">Gluten Free</option>
</select>

 Choose a drink

<select id="drink" name="drink">
  <option value="none">None</option>
  <option value="rootbeer">Root Beer</option>
  <option value="coke">Coke</option>
  <option value="diet coke">Diet Coke</option>
  <option value="dr pepper">Dr Pepper</option>
</select>
<input type="submit" name="submit" value="Submit"/>
</form>

Body:
Seems like you are not running the query.

// sql
$sql = "INSERT INTO order_info(drink,cheese,veggies,meat,sauce,crust,size)
VALUES('$value','$value2','$value3','$value4','$value5','$value6','$value7')";

// run query
mysqli_query($conn, $sql);

// or
$conn->query($sql);


问:
My bootstrap modal only works on the index.html page
It will not toggle and open on my other 2 pages.

            <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

        </button>
            Sponge Bob Square-Pants

                        About (current)

                        Portfolio

                        Contact

    ```

https://lonniewhite.github.io/SpongeBobSquarePants-JobPortfolio/

答:
1) you must include the navbar in every page you want it to appear

2) you have to include bootstrap and jquery in every page that contains the navbar. in the head tag, be sure you wrote this:

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</code>```

EDIT: also, be sure that "portfolio.html" and "contact.html" are written correctly and are in the same folder as index.php

Body:
It will not toggle and open on my other 2 pages.

            <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

        </button>
            Sponge Bob Square-Pants

                        About (current)

                        Portfolio

                        Contact

https://lonniewhite.github.io/SpongeBobSquarePants-JobPortfolio/

Body:
1) you must include the navbar in every page you want it to appear

2) you have to include bootstrap and jquery in every page that contains the navbar. in the head tag, be sure you wrote this:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

EDIT: also, be sure that "portfolio.html" and "contact.html" are written correctly and are in the same folder as index.php


问:
PHP - compatibility of <?= shortcut

Possible Duplicates:

  Are PHP short tags acceptable to use?

  Reference - What does this symbol mean in PHP?

Hi Guys,

I can't seem to find any information about the <?= shortcut of php.
Does anyone of you know more about that?

Thanks in advance!

答:
The manual entry on these short tags has this to say about compatibility

Using short tags should be avoided when
  developing applications or libraries
  that are meant for redistribution, or
  deployment on PHP servers which are
  not under your control, because short
  tags may not be supported on the
  target server. For portable,
  redistributable code, be sure not to
  use short tags.

ContentLicense: CC BY-SA 2.5

Title: PHP - compatibility of <?= shortcut


问:
Change AD Password with Java
I have a good connection to AD. I can authenticate and check error messages from failed auths.

The issue I'm having comes from trying to change the password. I have an LDAPContext established at this point (yes it is an SSL connection). The issue comes from not knowing what value to use in the "username" parameter. I've tried all variations I can think of and end up getting one of three errors:

A) NO_OBJECT - I'm assuming this means it is connecting to AD properly but can't find what I'm looking for.

B) DIR_ERROR - I'm assuming this means it can get into AD properly but doesn't know wtf I want it to do after that.

C) Some type of ref error that only happens when I don't qualify the DC, so I think that's pretty much a given.

Here is the code I am using:

```<code>public void changePassword(String username, String password) {
    ModificationItem[] mods = new ModificationItem[1];
    String newQuotedPassword = "\"" + password + "\"";
    byte[] newUnicodePassword = newQuotedPassword.getBytes();
    try {
        newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd", newUnicodePassword));
    try {

        ldapContext.modifyAttributes(username, mods);
    } catch (NamingException e) {
        System.out.println("Error changing password for '" + username + "': " + e.getMessage());
        e.printStackTrace();
    }
}
</code>```

答:
Here is a working example:

Main.java:

```<code>package io.fouad.ldap;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import java.io.UnsupportedEncodingException;
import java.util.Hashtable;

public class Main
{
    public static void main(String[] args)
    {
        final String LDAP_SERVERS = "ldap://AD_SERVER:636 ldap://AD_SERVER2:636"; // separated by single spaces
        final String LDAP_CONNECT_TIMEOUT_MS = "10000"; // 10 seconds
        final String LDAP_READ_TIMEOUT_MS = "10000"; // 10 seconds
        final String AUTHENTICATION_DOMAIN = "domain.com";
        final String USERNAME = "username";
        final String OLD_PASSWORD = "123";
        final String NEW_PASSWORD = "456";
        final String TARGET_BASE_DN = "dc=domain,dc=com";

        Hashtable<String, String> ldapEnv = new Hashtable<>();
        ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        ldapEnv.put(Context.PROVIDER_URL, LDAP_SERVERS);
        ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
        ldapEnv.put("java.naming.ldap.version", "3");
        ldapEnv.put(Context.SECURITY_PRINCIPAL, USERNAME + "@" + AUTHENTICATION_DOMAIN);
        ldapEnv.put(Context.SECURITY_CREDENTIALS, OLD_PASSWORD);
        ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
        ldapEnv.put("java.naming.ldap.factory.socket", "io.fouad.ldap.MySSLSocketFactory");
        //ldapEnv.put("com.sun.jndi.ldap.connect.timeout", LDAP_CONNECT_TIMEOUT_MS);
        //ldapEnv.put("com.sun.jndi.ldap.read.timeout", LDAP_READ_TIMEOUT_MS);
        DirContext ldapContext = null;

        try
        {
            ldapContext = new InitialDirContext(ldapEnv);
        }
        catch(AuthenticationException e)
        {
            System.out.println("Wrong username/password!");
            e.printStackTrace();
        }
        catch(NamingException e)
        {
            e.printStackTrace();
        }

        if(ldapContext == null) return;

        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        NamingEnumeration objects = null;
        try
        {
            objects = ldapContext.search(TARGET_BASE_DN, String.format("(&(objectClass=user)(sAMAccountName=%s))", USERNAME), searchControls);
        }
        catch(NamingException e)
        {
            e.printStackTrace();
        }

        if(objects == null) return;

        try
        {
            if(objects.hasMore())
            {
                SearchResult entry = (SearchResult) objects.next();
                ModificationItem[] mods = new ModificationItem[2];
                mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute("unicodePwd", getPasswordByteArray(OLD_PASSWORD)));
                mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("unicodePwd", getPasswordByteArray(NEW_PASSWORD)));
                ldapContext.modifyAttributes(entry.getName() + "," + TARGET_BASE_DN, mods);

                System.out.println("Successfully changed the password!");
            }
            else
            {
                System.out.println("User (" + USERNAME + ") was not found!");
            }
        }
        catch(NamingException e)
        {
            e.printStackTrace();
        }

        System.out.println("DONE!");

    }

    private static byte[] getPasswordByteArray(String password)
    {
        String quotedPassword = "\"" + password + "\"";
        try
        {
            return quotedPassword.getBytes("UTF-16LE");
        }
        catch(UnsupportedEncodingException e)
        {
            e.printStackTrace();
            return null;
        }
    }
}
</code>```

MySSLSocketFactory.java: (Use it at your own risk)

```<code>package io.fouad.ldap;

import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

public class MySSLSocketFactory extends SSLSocketFactory
{
    private SSLSocketFactory socketFactory;

    public MySSLSocketFactory()
    {
        try
        {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] {new X509TrustManager()
            {
                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s){}

                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s){}

                @Override
                public X509Certificate[] getAcceptedIssuers()
                {
                    return new X509Certificate[0];
                }
            }}, new SecureRandom());

            socketFactory = ctx.getSocketFactory();
        }
        catch(Exception ex)
        {
            ex.printStackTrace(System.err);
        }
    }

    public static SocketFactory getDefault()
    {
        return new MySSLSocketFactory();
    }

    @Override
    public String[] getDefaultCipherSuites()
    {
        return socketFactory.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites()
    {
        return socketFactory.getSupportedCipherSuites();
    }

    @Override
    public Socket createSocket(Socket socket, String string, int i, boolean bln) throws IOException
    {
        return socketFactory.createSocket(socket, string, i, bln);
    }

    @Override
    public Socket createSocket(String string, int i) throws IOException
    {
        return socketFactory.createSocket(string, i);
    }

    @Override
    public Socket createSocket(String string, int i, InetAddress ia, int i1) throws IOException
    {
        return socketFactory.createSocket(string, i, ia, i1);
    }

    @Override
    public Socket createSocket(InetAddress ia, int i) throws IOException
    {
        return socketFactory.createSocket(ia, i);
    }

    @Override
    public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException
    {
        return socketFactory.createSocket(ia, i, ia1, i1);
    }
}
</code>```

OwnerDisplayName: Gonzo

LastEditorDisplayName: Gonzo

Title: Change AD Password with Java

Body:
I have a good connection to AD. I can authenticate and check error messages from failed auths.

The issue I'm having comes from trying to change the password. I have an LDAPContext established at this point (yes it is an SSL connection). The issue comes from not knowing what value to use in the "username" parameter. I've tried all variations I can think of and end up getting one of three errors:

A) NO_OBJECT - I'm assuming this means it is connecting to AD properly but can't find what I'm looking for.

B) DIR_ERROR - I'm assuming this means it can get into AD properly but doesn't know wtf I want it to do after that.

C) Some type of ref error that only happens when I don't qualify the DC, so I think that's pretty much a given.

Here is the code I am using:

public void changePassword(String username, String password) {
    ModificationItem[] mods = new ModificationItem[1];
    String newQuotedPassword = "\"" + password + "\"";
    byte[] newUnicodePassword = newQuotedPassword.getBytes();
    try {
        newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd", newUnicodePassword));
    try {

        ldapContext.modifyAttributes(username, mods);
    } catch (NamingException e) {
        System.out.println("Error changing password for '" + username + "': " + e.getMessage());
        e.printStackTrace();
    }
}

Body:
Here is a working example:

Main.java:

package io.fouad.ldap;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import java.io.UnsupportedEncodingException;
import java.util.Hashtable;

public class Main
{
    public static void main(String[] args)
    {
        final String LDAP_SERVERS = "ldap://AD_SERVER:636 ldap://AD_SERVER2:636"; // separated by single spaces
        final String LDAP_CONNECT_TIMEOUT_MS = "10000"; // 10 seconds
        final String LDAP_READ_TIMEOUT_MS = "10000"; // 10 seconds
        final String AUTHENTICATION_DOMAIN = "domain.com";
        final String USERNAME = "username";
        final String OLD_PASSWORD = "123";
        final String NEW_PASSWORD = "456";
        final String TARGET_BASE_DN = "dc=domain,dc=com";

        Hashtable<String, String> ldapEnv = new Hashtable<>();
        ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        ldapEnv.put(Context.PROVIDER_URL, LDAP_SERVERS);
        ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
        ldapEnv.put("java.naming.ldap.version", "3");
        ldapEnv.put(Context.SECURITY_PRINCIPAL, USERNAME + "@" + AUTHENTICATION_DOMAIN);
        ldapEnv.put(Context.SECURITY_CREDENTIALS, OLD_PASSWORD);
        ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
        ldapEnv.put("java.naming.ldap.factory.socket", "io.fouad.ldap.MySSLSocketFactory");
        //ldapEnv.put("com.sun.jndi.ldap.connect.timeout", LDAP_CONNECT_TIMEOUT_MS);
        //ldapEnv.put("com.sun.jndi.ldap.read.timeout", LDAP_READ_TIMEOUT_MS);
        DirContext ldapContext = null;

        try
        {
            ldapContext = new InitialDirContext(ldapEnv);
        }
        catch(AuthenticationException e)
        {
            System.out.println("Wrong username/password!");
            e.printStackTrace();
        }
        catch(NamingException e)
        {
            e.printStackTrace();
        }

        if(ldapContext == null) return;

        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        NamingEnumeration objects = null;
        try
        {
            objects = ldapContext.search(TARGET_BASE_DN, String.format("(&(objectClass=user)(sAMAccountName=%s))", USERNAME), searchControls);
        }
        catch(NamingException e)
        {
            e.printStackTrace();
        }

        if(objects == null) return;

        try
        {
            if(objects.hasMore())
            {
                SearchResult entry = (SearchResult) objects.next();
                ModificationItem[] mods = new ModificationItem[2];
                mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute("unicodePwd", getPasswordByteArray(OLD_PASSWORD)));
                mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("unicodePwd", getPasswordByteArray(NEW_PASSWORD)));
                ldapContext.modifyAttributes(entry.getName() + "," + TARGET_BASE_DN, mods);

                System.out.println("Successfully changed the password!");
            }
            else
            {
                System.out.println("User (" + USERNAME + ") was not found!");
            }
        }
        catch(NamingException e)
        {
            e.printStackTrace();
        }

        System.out.println("DONE!");

    }

    private static byte[] getPasswordByteArray(String password)
    {
        String quotedPassword = "\"" + password + "\"";
        try
        {
            return quotedPassword.getBytes("UTF-16LE");
        }
        catch(UnsupportedEncodingException e)
        {
            e.printStackTrace();
            return null;
        }
    }
}

MySSLSocketFactory.java: (Use it at your own risk)

package io.fouad.ldap;

import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

public class MySSLSocketFactory extends SSLSocketFactory
{
    private SSLSocketFactory socketFactory;

    public MySSLSocketFactory()
    {
        try
        {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, new TrustManager[] {new X509TrustManager()
            {
                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s){}

                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s){}

                @Override
                public X509Certificate[] getAcceptedIssuers()
                {
                    return new X509Certificate[0];
                }
            }}, new SecureRandom());

            socketFactory = ctx.getSocketFactory();
        }
        catch(Exception ex)
        {
            ex.printStackTrace(System.err);
        }
    }

    public static SocketFactory getDefault()
    {
        return new MySSLSocketFactory();
    }

    @Override
    public String[] getDefaultCipherSuites()
    {
        return socketFactory.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites()
    {
        return socketFactory.getSupportedCipherSuites();
    }

    @Override
    public Socket createSocket(Socket socket, String string, int i, boolean bln) throws IOException
    {
        return socketFactory.createSocket(socket, string, i, bln);
    }

    @Override
    public Socket createSocket(String string, int i) throws IOException
    {
        return socketFactory.createSocket(string, i);
    }

    @Override
    public Socket createSocket(String string, int i, InetAddress ia, int i1) throws IOException
    {
        return socketFactory.createSocket(string, i, ia, i1);
    }

    @Override
    public Socket createSocket(InetAddress ia, int i) throws IOException
    {
        return socketFactory.createSocket(ia, i);
    }

    @Override
    public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException
    {
        return socketFactory.createSocket(ia, i, ia1, i1);
    }
}


问:
Where can i save information to be displayed by my Android App
where should i save the information i want my app to display When selected,with out using a server because i want my content(includes a combination of text and images) to be available offline and which format can i use to this in Android?</p>

答:
Storage options, pretty nice listing and explanation

Shared Preferences: Store private primitive data in key-value pairs, is a good idea for small simple data like flags or user preferences.

Internal Storage: Store private data on the device memory, basically you can write files to a private area for your applications, will also show up as space consumed by your application user data in settings.

External Storage: Store public data on the shared external storage, same as internal storage but the directly is public and not private to your application, user and other applications can see this directory.

SQLite Databases: Store structured data in a private database, you can place the database where you want (internal/external) provides some nice mechanism for CRUD operations.

Network Connection: Store data on the web with your own network
server.


问:
How can I give a name to each module in ModuleList?
I have the following component in my model:

```<code>feedfnn = []
for task_name, num_class in self.tasks:
    if self.config.nonlinear_fc:
        ffnn = nn.Sequential(OrderedDict([
            ('dropout1', nn.Dropout(self.config.dropout_fc)),
            ('dense1', nn.Linear(self.config.nhid * self.num_directions * 8, self.config.fc_dim)),
            ('tanh', nn.Tanh()),
            ('dropout2', nn.Dropout(self.config.dropout_fc)),
            ('dense2', nn.Linear(self.config.fc_dim, self.config.fc_dim)),
            ('tanh', nn.Tanh()),
            ('dropout3', nn.Dropout(self.config.dropout_fc)),
            ('dense3', nn.Linear(self.config.fc_dim, num_class))
        ]))
    else:
        ffnn = nn.Sequential(OrderedDict([
            ('dropout1', nn.Dropout(self.config.dropout_fc)),
            ('dense1', nn.Linear(self.config.nhid * self.num_directions * 8, self.config.fc_dim)),
            ('dropout2', nn.Dropout(self.config.dropout_fc)),
            ('dense2', nn.Linear(self.config.fc_dim, self.config.fc_dim)),
            ('dropout3', nn.Dropout(self.config.dropout_fc)),
            ('dense3', nn.Linear(self.config.fc_dim, num_class))
        ]))
    feedfnn.append(ffnn)
self.ffnn = nn.ModuleList(feedfnn)
</code>```

When I print my model, I get the description of the above component as:

```<code>(ffnn): ModuleList (
(0): Sequential (
  (dropout1): Dropout (p = 0)
  (dense1): Linear (4096 -> 512)
  (dropout2): Dropout (p = 0)
  (dense2): Linear (512 -> 512)
  (dropout3): Dropout (p = 0)
  (dense3): Linear (512 -> 2)
)
(1): Sequential (
  (dropout1): Dropout (p = 0)
  (dense1): Linear (4096 -> 512)
  (dropout2): Dropout (p = 0)
  (dense2): Linear (512 -> 512)
  (dropout3): Dropout (p = 0)
  (dense3): Linear (512 -> 3)
)
(2): Sequential (
  (dropout1): Dropout (p = 0)
  (dense1): Linear (4096 -> 512)
  (dropout2): Dropout (p = 0)
  (dense2): Linear (512 -> 512)
  (dropout3): Dropout (p = 0)
  (dense3): Linear (512 -> 3)
)
)
</code>```

Can I put a specific name like (task1): Sequential, (task2): Sequential instead of (0): Sequential, (1): Sequential?

答:
That's straightforward.

Simply start with an empty ModuleListand then use add_module for it. For example,

```<code>import torch.nn as nn
from collections import OrderedDict

final_module_list = nn.ModuleList()

a_sequential_module_with_names = nn.Sequential(OrderedDict([
        ('dropout1', nn.Dropout(0.1)),
        ('dense1', nn.Linear(10, 10)),
        ('tanh', nn.Tanh()),
        ('dropout2', nn.Dropout(0.1)),
        ('dense2', nn.Linear(10, 10)),
        ('tanh', nn.Tanh()),
        ('dropout3', nn.Dropout(0.1)),
        ('dense3', nn.Linear(10, 10))]))

final_module_list.add_module('Stage 1', a_sequential_module_with_names)
final_module_list.add_module('Stage 2', a_sequential_module_with_names)
etc.
</code>```

Body:
I have the following component in my model:

feedfnn = []
for task_name, num_class in self.tasks:
    if self.config.nonlinear_fc:
        ffnn = nn.Sequential(OrderedDict([
            ('dropout1', nn.Dropout(self.config.dropout_fc)),
            ('dense1', nn.Linear(self.config.nhid * self.num_directions * 8, self.config.fc_dim)),
            ('tanh', nn.Tanh()),
            ('dropout2', nn.Dropout(self.config.dropout_fc)),
            ('dense2', nn.Linear(self.config.fc_dim, self.config.fc_dim)),
            ('tanh', nn.Tanh()),
            ('dropout3', nn.Dropout(self.config.dropout_fc)),
            ('dense3', nn.Linear(self.config.fc_dim, num_class))
        ]))
    else:
        ffnn = nn.Sequential(OrderedDict([
            ('dropout1', nn.Dropout(self.config.dropout_fc)),
            ('dense1', nn.Linear(self.config.nhid * self.num_directions * 8, self.config.fc_dim)),
            ('dropout2', nn.Dropout(self.config.dropout_fc)),
            ('dense2', nn.Linear(self.config.fc_dim, self.config.fc_dim)),
            ('dropout3', nn.Dropout(self.config.dropout_fc)),
            ('dense3', nn.Linear(self.config.fc_dim, num_class))
        ]))
    feedfnn.append(ffnn)
self.ffnn = nn.ModuleList(feedfnn)

When I print my model, I get the description of the above component as:

(ffnn): ModuleList (
(0): Sequential (
  (dropout1): Dropout (p = 0)
  (dense1): Linear (4096 -> 512)
  (dropout2): Dropout (p = 0)
  (dense2): Linear (512 -> 512)
  (dropout3): Dropout (p = 0)
  (dense3): Linear (512 -> 2)
)
(1): Sequential (
  (dropout1): Dropout (p = 0)
  (dense1): Linear (4096 -> 512)
  (dropout2): Dropout (p = 0)
  (dense2): Linear (512 -> 512)
  (dropout3): Dropout (p = 0)
  (dense3): Linear (512 -> 3)
)
(2): Sequential (
  (dropout1): Dropout (p = 0)
  (dense1): Linear (4096 -> 512)
  (dropout2): Dropout (p = 0)
  (dense2): Linear (512 -> 512)
  (dropout3): Dropout (p = 0)
  (dense3): Linear (512 -> 3)
)
)

Can I put a specific name like (task1): Sequential, (task2): Sequential instead of (0): Sequential, (1): Sequential?

Body:
That's straightforward.

Simply start with an empty ModuleListand then use add_module for it. For example,

import torch.nn as nn
from collections import OrderedDict

final_module_list = nn.ModuleList()

a_sequential_module_with_names = nn.Sequential(OrderedDict([
        ('dropout1', nn.Dropout(0.1)),
        ('dense1', nn.Linear(10, 10)),
        ('tanh', nn.Tanh()),
        ('dropout2', nn.Dropout(0.1)),
        ('dense2', nn.Linear(10, 10)),
        ('tanh', nn.Tanh()),
        ('dropout3', nn.Dropout(0.1)),
        ('dense3', nn.Linear(10, 10))]))

final_module_list.add_module('Stage 1', a_sequential_module_with_names)
final_module_list.add_module('Stage 2', a_sequential_module_with_names)
etc.


问:
Get the result console in text file java
I would like to know how to get the result of eclipse console in text file.
I tried this code but it didn't work...the file still empty

```<code>PrintStream out = new PrintStream(new FileOutputStream("/home/nadhmanovic/Bureau/output.txt"));
System.setOut(out);
</code>```

Any idea why this is so?

答:
You will not get contents of your file because every time you call your code executed your file will get empty

To show fie contents you can use this

```<code>File f = new File("U:\\abc.txt");
Scanner in =new Scanner(f);
while(in.hasNext())
{
    System.out.println(in.next());
}
</code>```

Body:
I would like to know how to get the result of eclipse console in text file.
I tried this code but it didn't work...the file still empty

PrintStream out = new PrintStream(new FileOutputStream("/home/nadhmanovic/Bureau/output.txt"));
System.setOut(out);

Any idea why this is so?

Body:
You will not get contents of your file because every time you call your code executed your file will get empty

To show fie contents you can use this

File f = new File("U:\\abc.txt");
Scanner in =new Scanner(f);
while(in.hasNext())
{
    System.out.println(in.next());
}


问:
Quotation Marks Causing Error on Page
I really hope someone can help me.  I've been banging my head against the wall with this one :(.

I have the following code that is driving me nuts

In my PHP file I have entered the following code to display a series of A-Z Links:

```<code><div>
 <ul id="AZList">
     <li><a id="LetterLink1" href="javascript:showonlyone('LetterList1');">#</a></li>
  <?php

   $lettercounter=1;
   for ($i=65; $i<=90; $i++){

      $lettercounter=$lettercounter+1;
      $LetterLinkLbL="ListLetter".$lettercounter;
?>

          <li><a id="LetterLink<?php echo $lettercounter ?>" href="javascript:showonlyone('<?php echo $LetterLinkLbL ?>');"><?php echo chr($i) ?></a></li>

  <?php } ?>
    </ul>

</div>
</code>```

But when I view the source file it displays as

```<code>  <li><a id="LetterLink1"  href="javascript:showonlyone("LetterList1');">#</a></li>

      <li><a id="LetterLink2"  href="javascript:showonlyone("ListLetter2');">A</a></li>

      <li><a id="LetterLink3"  href="javascript:showonlyone("ListLetter3');">B</a></li>
</code>```

Which is causing an error on the page

The first one should read:

```<code> <li><a id="LetterLink1"  href="javascript:showonlyone('LetterList1');">#</a></li>
</code>```

Does anyone know how I can get the quotes to display correctly?

I've just uploaded the file from my laptop to the Remote server and it is working as it should without me making any changes to the file.

I did confirm that I was working on and viewing the same file, by writing an echo statement to the page.

Why would it be showing like this on my localhost?  Does anyone have an idea what he issue could be?

Thank you for all your comments by the way

答:
Why don't you check out functions like htmlspecialentities(), which will escape and convert these ambiguous characters. also do check your text editor's charset encoding and escape quotes if necessary by applying preceding backslashes() to the single quote.

if you're escaping quotes, this will also work in PHP:

```<code>href="javascript:showonlyone(\"<?php echo $LetterLinkLbL ?>\");">
</code>```

btw as an aside: <?php echo ... ?> can be written in shorthand and reduced to <?= ... ?> without even the ending semicolon(;)

Title: Quotation Marks Causing Error on Page

Body:
I really hope someone can help me.  I've been banging my head against the wall with this one :(.

I have the following code that is driving me nuts

In my PHP file I have entered the following code to display a series of A-Z Links:

#

  <?php

   $lettercounter=1;
   for ($i=65; $i<=90; $i++){

      $lettercounter=$lettercounter+1;
      $LetterLinkLbL="ListLetter".$lettercounter;
?>

<a id="LetterLink<?php echo $lettercounter ?>" href="javascript:showonlyone('<?php echo $LetterLinkLbL ?>');"><?php echo chr($i) ?>

  <?php } ?>

But when I view the source file it displays as

#

A

B

Which is causing an error on the page

The first one should read:

#

Does anyone know how I can get the quotes to display correctly?

I've just uploaded the file from my laptop to the Remote server and it is working as it should without me making any changes to the file.

I did confirm that I was working on and viewing the same file, by writing an echo statement to the page.

Why would it be showing like this on my localhost?  Does anyone have an idea what he issue could be?

Thank you for all your comments by the way

Body:
Why don't you check out functions like htmlspecialentities(), which will escape and convert these ambiguous characters. also do check your text editor's charset encoding and escape quotes if necessary by applying preceding backslashes() to the single quote.

if you're escaping quotes, this will also work in PHP:

href="javascript:showonlyone(\"<?php echo $LetterLinkLbL ?>\");">

btw as an aside: <?php echo ... ?> can be written in shorthand and reduced to <?= ... ?> without even the ending semicolon(;)


问:
OpenJPEG: How to set the stepsizes used for quantization?
I have a JP2-file that I decompress and want to recompress Using OpenJPEG.
For the original ojp_dump returns:

```<code>stepsizes (m,e)=(2046,12)
</code>```

The re-encoded imgage has many stepsizes:

```<code>stepsizes (m,e)=(1824,14) (1776,14) (1776,14) (1728,14) (1792,13) (1792,13) (1760,13) (1872,12) (1872,12) (1896,12) (5,10) (5,10) (71,10) (2003,10) (2003,10) (1890,10)
</code>```

And the recompressed image-file is much larger than the original.
Any idea what I'm doing wrong?

Thanks!

答: Re-compression is known to be a lossy operation. And if you try to crank up the quality during re-compression step to avoid the loss, you end up with a much larger image than the original. That's why re-compression should be avoided whenever possible.</p>

Body:
I have a JP2-file that I decompress and want to recompress Using OpenJPEG.
For the original ojp_dump returns:

stepsizes (m,e)=(2046,12)

The re-encoded imgage has many stepsizes:

stepsizes (m,e)=(1824,14) (1776,14) (1776,14) (1728,14) (1792,13) (1792,13) (1760,13) (1872,12) (1872,12) (1896,12) (5,10) (5,10) (71,10) (2003,10) (2003,10) (1890,10)

And the recompressed image-file is much larger than the original.
Any idea what I'm doing wrong?

Thanks!


问:
Creating a document in firestore using cloud functions
After authenticating a user in my app i want to create a cloud functions that creates a user profile document for them in my firestore userProfile collection.

This is my entire index.js file for the cloud function

```<code>// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

//function that triggers on user creation
//this function will create a user profile in firestore database
exports.createProfile = functions.auth.user().onCreate(event => {
    // Do something after a new user account is created
    return admin.firestore().ref(`/userProfile/${event.data.uid}`).set({
        email: event.data.email
    });
});
</code>```

Here is the error i am receiving

```<code>TypeError: admin.firestore(...).ref is not a function
    at exports.createProfile.functions.auth.user.onCreate.event (/user_code/index.js:13:30)
    at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:59:27)
    at next (native)
    at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
    at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
    at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:53:36)
    at /var/tmp/worker/worker.js:695:26
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)
</code>```

In the firestore cloud database I have a collection called userProfile where a document should be created with the unique id given to a user after authentication

答:
admin.firestore() returns an instance of a Firestore object. As you can see from the API docs, the Firestore class doesn't have a ref() method.  You're probably confusing it with the Realtime Database API.

Firestore requires you to organize documents within collections. To reach into a document, you could do this:

```<code>const doc = admin.firestore().doc(`/userProfile/${event.data.uid}`)
</code>```

Here, doc is a DocumentReference.  You can then set the contents of that document like this:

```<code>doc.set({ email: event.data.email })
</code>```

Be sure to read the Firestore documentation to understand how to set up Firestore - there are many places where it's different than Realtime Database.

Body:
After authenticating a user in my app i want to create a cloud functions that creates a user profile document for them in my firestore userProfile collection.

This is my entire index.js file for the cloud function

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

//function that triggers on user creation
//this function will create a user profile in firestore database
exports.createProfile = functions.auth.user().onCreate(event => {
    // Do something after a new user account is created
    return admin.firestore().ref(`/userProfile/${event.data.uid}`).set({
        email: event.data.email
    });
});

Here is the error i am receiving

TypeError: admin.firestore(...).ref is not a function
    at exports.createProfile.functions.auth.user.onCreate.event (/user_code/index.js:13:30)
    at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:59:27)
    at next (native)
    at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
    at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
    at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:53:36)
    at /var/tmp/worker/worker.js:695:26
    at process._tickDomainCallback (internal/process/next_tick.js:135:7)

In the firestore cloud database I have a collection called userProfile where a document should be created with the unique id given to a user after authentication

Body:
admin.firestore() returns an instance of a Firestore object. As you can see from the API docs, the Firestore class doesn't have a ref() method.  You're probably confusing it with the Realtime Database API.

Firestore requires you to organize documents within collections. To reach into a document, you could do this:

const doc = admin.firestore().doc(`/userProfile/${event.data.uid}`)

Here, doc is a DocumentReference.  You can then set the contents of that document like this:

doc.set({ email: event.data.email })

Be sure to read the Firestore documentation to understand how to set up Firestore - there are many places where it's different than Realtime Database.


问:
IBM Cloud Private 2.1.0 Console doesn't work after restart
IBM Cloud Private 2.1 installation, configuration is a demo config, 1 x master and proxy and 1 x worker node.

Installation runs through fine and once completed I am able to logon to the GUI. After a reboot the GUI doesn't come up and I cant login in.

I have disabled the firewall just in case by still no luck.

--> ran the following command to get status of PODS (as WebUI is unavailable)

kubectl -s 127.0.0.1:8888 -n kube-system get pods

-- > output

```<code>[root@cpmaster ~]# kubectl -s 127.0.0.1:8888 -n kube-system get pods
NAME                                               READY     STATUS             RESTARTS   AGE
calico-node-ppc64le-496xm                          2/2       Running            10         15d
filebeat-ds-ppc64le-qssl2                          1/1       Running            5          15d
k8s-etcd-X.X.X.X                                   1/1       Running            5          15d
k8s-mariadb-X.X.X.X                                1/1       Running            5          15d
k8s-master-X.X.X.X                                 2/3       CrashLoopBackOff   559        4m
k8s-proxy-X.X.X.X                                  1/1       Running            5          15d
metering-reader-ppc64le-gcc8w                      1/1       Running            5          15d
monitoring-prometheus-nodeexporter-ppc64le-zq8ls   1/1       Running            5          15d
</code>```

Looks like I have a problem with the k2s-master POD

答:
You can see where ui pod is running or not:

kubectl -s 127.0.0.1:8888 -n kube-system get pods |grep platform-ui

Sometimes, it takes a while for the the pod to come back after machine reboot.

You can also check the logs for the platform-ui container to trace the issue:

```<code>#enter code here # get container-id
docker ps | grep platform-ui
# see the logs
docker logs container-id
</code>```

Body:
IBM Cloud Private 2.1 installation, configuration is a demo config, 1 x master and proxy and 1 x worker node.

Installation runs through fine and once completed I am able to logon to the GUI. After a reboot the GUI doesn't come up and I cant login in.

I have disabled the firewall just in case by still no luck.

--> ran the following command to get status of PODS (as WebUI is unavailable)

kubectl -s 127.0.0.1:8888 -n kube-system get pods

-- > output

[root@cpmaster ~]# kubectl -s 127.0.0.1:8888 -n kube-system get pods
NAME                                               READY     STATUS             RESTARTS   AGE
calico-node-ppc64le-496xm                          2/2       Running            10         15d
filebeat-ds-ppc64le-qssl2                          1/1       Running            5          15d
k8s-etcd-X.X.X.X                                   1/1       Running            5          15d
k8s-mariadb-X.X.X.X                                1/1       Running            5          15d
k8s-master-X.X.X.X                                 2/3       CrashLoopBackOff   559        4m
k8s-proxy-X.X.X.X                                  1/1       Running            5          15d
metering-reader-ppc64le-gcc8w                      1/1       Running            5          15d
monitoring-prometheus-nodeexporter-ppc64le-zq8ls   1/1       Running            5          15d

Looks like I have a problem with the k2s-master POD

Body:
You can see where ui pod is running or not:

kubectl -s 127.0.0.1:8888 -n kube-system get pods |grep platform-ui

Sometimes, it takes a while for the the pod to come back after machine reboot.

You can also check the logs for the platform-ui container to trace the issue:

#enter code here # get container-id
docker ps | grep platform-ui
# see the logs
docker logs container-id


问:
How the host's forward and backward DNS entries match in java application makes it secure from DNS spoofing
I am using fortify and it is showing the vulnerability by which the attacker can do DNS spoofing while I am trying to get hostname in the java application.
I have got one solution that by matching forward DNS and Reverse DNS entries it can be avoided. But how it is useful and how can I implement it, I am not able to find it.
Fortify shows vulnerability at this line

Link for line

Fortify is showing recommendations like this:

Recommendations:

You can increase confidence in a domain name lookup if you check to
  make sure that the host's forward and backward DNS entries match.
  Attackers will not be able to spoof both the forward and the reverse
  DNS entries without controlling the nameservers for the target domain.
  This is not a foolproof approach however: attackers may be able to
  convince the domain registrar to turn over the domain to a malicious
  nameserver.  Basing authentication on DNS entries is simply a risky
  proposition.

Any help is appreciated and another solutions are also welcome.

Thanks in advance.

答:
I assume it's something like this:</p>

```<code>    final String hostname = "google.com";
    final String ipAddress = "123.123.123.123";
    final InetAddress byIpAddress = InetAddress.getByName(ipAddress);
    boolean forwardCheck = byIpAddress.getHostName().equals(hostname);
    final InetAddress byHostName = InetAddress.getByName(hostname);
    boolean reverseCheck = byHostName.getHostAddress().equals(ipAddress);
    if (reverseCheck && forwardCheck) {
        // perform your logic
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I assume it's something like this:

    final String hostname = "google.com";
    final String ipAddress = "123.123.123.123";
    final InetAddress byIpAddress = InetAddress.getByName(ipAddress);
    boolean forwardCheck = byIpAddress.getHostName().equals(hostname);
    final InetAddress byHostName = InetAddress.getByName(hostname);
    boolean reverseCheck = byHostName.getHostAddress().equals(ipAddress);
    if (reverseCheck && forwardCheck) {
        // perform your logic
    }


问:
Redirect in React with Typescript
I am working on React with Typescript. "Redirect" doesn't seem to work for me.
I don't know what the problem is.

```<code>import * as React from "react"
import { TextField } from 'office-ui-fabric-react/lib/TextField';
import { PrimaryButton } from 'office-ui-fabric-react/lib/Button';
import store from "./ToDoStore"
import { Redirect} from "react-router-dom";
export class AddTodo extends React.Component {

refs: {
    name: (HTMLInputElement);
    description: (HTMLInputElement);
}

addTodo() {
    store.addTodo({ name: this.refs.name.value, description: this.refs.description.value })
    alert("Task added successfully");

 <Redirect to="/home" push/>
}

render() {

    return (
        <div id="addtodo">
            <TextField
                label='Add Todo' ref="name"
            />
            <br />
            <TextField
                label='Add Description' ref="description"
            />
            <br />
            <PrimaryButton text="Add" onClick={this.addTodo.bind(this)} />
        </div>
    )
}
</code>```

}

答:
You can programmatically navigate to another page using this.props.history.push.
    export your class with react-router-dom withRouter(AddTodo) for history to work like

```<code>//Import
import { withRouter } from "react-router-dom";
</code>```

Your component will be

```<code>/*Your component*/
class AddTodo extends React.Component {
    ..your code goes here
}

export default withRouter(AddTodo);
</code>```

And in your addTodo method

```<code>addTodo() {
     // Task added successfully
    if(success) { // Go to home page if success
        this.props.history.push('/home');
    }
}
</code>```

Title: Redirect in React with Typescript

Body:
I am working on React with Typescript. "Redirect" doesn't seem to work for me.
I don't know what the problem is.

import * as React from "react"
import { TextField } from 'office-ui-fabric-react/lib/TextField';
import { PrimaryButton } from 'office-ui-fabric-react/lib/Button';
import store from "./ToDoStore"
import { Redirect} from "react-router-dom";
export class AddTodo extends React.Component {

refs: {
    name: (HTMLInputElement);
    description: (HTMLInputElement);
}

addTodo() {
    store.addTodo({ name: this.refs.name.value, description: this.refs.description.value })
    alert("Task added successfully");

 <Redirect to="/home" push/>
}

render() {

    return (

            <TextField
                label='Add Todo' ref="name"
            />

            <TextField
                label='Add Description' ref="description"
            />

            <PrimaryButton text="Add" onClick={this.addTodo.bind(this)} />

    )
}

}

Body:
You can programmatically navigate to another page using this.props.history.push.
    export your class with react-router-dom withRouter(AddTodo) for history to work like

//Import
import { withRouter } from "react-router-dom";

Your component will be

/*Your component*/
class AddTodo extends React.Component {
    ..your code goes here
}

export default withRouter(AddTodo);

And in your addTodo method

addTodo() {
     // Task added successfully
    if(success) { // Go to home page if success
        this.props.history.push('/home');
    }
}


问:
mongod: error while loading shared libraries: libssl.so.10 libcrypto.so.10
Problem

I downloaded the mongodb 3.0.7 tar files. Then I added the bin directory to my path:

```<code>export PATH=<mongodb-install-directory>/bin:$PATH
</code>```

Then when I run the mongodb server:

```<code>mongod --fork --logpath "/home/me/mongolog" --dbpath "/home/me/data"
</code>```

I get this error:

```<code>mongod: error while loading shared libraries: libssl.so.10: cannot open shared object file: No such file or directory
</code>```

What I did

I tried this solution. In brief I updated my openssl:

```<code>sudo apt-get update
sudo apt-get install libssl1.0.0 libssl-dev
</code>```

and then:

```<code>cd /lib/x86_64-linux-gnu
sudo ln -s libssl.so.1.0.0 libssl.so.10
sudo ln -s libcrypto.so.1.0.0 libcrypto.so.10
</code>```

but it says that it cannot find libssl.so.10 and libcrypto.so.10. I don't know what to do!

答:
i had this same problem and what i did was

created /data/db in the root folder(i use a Linux distro)

then, mongod --dbpath ~/data/db/

then, mongo

i hope this helps anyone facing the same problem in future

Body:
Problem

I downloaded the mongodb 3.0.7 tar files. Then I added the bin directory to my path:

export PATH=<mongodb-install-directory>/bin:$PATH

Then when I run the mongodb server:

mongod --fork --logpath "/home/me/mongolog" --dbpath "/home/me/data"

I get this error:

mongod: error while loading shared libraries: libssl.so.10: cannot open shared object file: No such file or directory

What I did

I tried this solution. In brief I updated my openssl:

sudo apt-get update
sudo apt-get install libssl1.0.0 libssl-dev

and then:

cd /lib/x86_64-linux-gnu
sudo ln -s libssl.so.1.0.0 libssl.so.10
sudo ln -s libcrypto.so.1.0.0 libcrypto.so.10

but it says that it cannot find libssl.so.10 and libcrypto.so.10. I don't know what to do!


问:
How to add or remove spaces depending on user input (Ascii to hex, binary...)
I am trying to make it so you can convert user input (ASCII to hex, binary and more). My problem is when the user input has spaces I want the output also to have space and vise versa when there are no spaces also have no spaces.

```<code>    function asciiConverter(asciiInput) {
    var hexArray = [];
    var binArray = [];
    var decArray = [];
    for (var i = 0, length = asciiInput.length; i < length; i ++) {
        var hex = asciiInput.charCodeAt(i).toString(16);
        hexArray.push(hex);
        var binary = asciiInput.charCodeAt(i).toString(2);
        binArray.push(binary);
        var dec = asciiInput.charCodeAt(i).toString(2);
        decArray.push(dec);
    }
    // /g is a global match with regex
    var hexPrint = hexArray.toString().replace(/,20/g, " ").replace(/,/g, " ");
    document.write(hexPrint);
}
asciiConverter("123");
</code>```

Output:  31 32 33

answered my own down below

答:
Answered my own again:

```<code>var hexPrint = hexArray.toString().replace(/,20/g, " ").replace(/,/g, "");
</code>```

change

    .replace(/,/g, " ");

to

    .replace(/,/g, "");

Body:
I am trying to make it so you can convert user input (ASCII to hex, binary and more). My problem is when the user input has spaces I want the output also to have space and vise versa when there are no spaces also have no spaces.

    function asciiConverter(asciiInput) {
    var hexArray = [];
    var binArray = [];
    var decArray = [];
    for (var i = 0, length = asciiInput.length; i < length; i ++) {
        var hex = asciiInput.charCodeAt(i).toString(16);
        hexArray.push(hex);
        var binary = asciiInput.charCodeAt(i).toString(2);
        binArray.push(binary);
        var dec = asciiInput.charCodeAt(i).toString(2);
        decArray.push(dec);
    }
    // /g is a global match with regex
    var hexPrint = hexArray.toString().replace(/,20/g, " ").replace(/,/g, " ");
    document.write(hexPrint);
}
asciiConverter("123");

Output:  31 32 33

answered my own down below

Body:
Answered my own again:

var hexPrint = hexArray.toString().replace(/,20/g, " ").replace(/,/g, "");

change

    .replace(/,/g, " ");

to

    .replace(/,/g, "");


问:
LINQ query multiple conditions
I need to have multiple conditions in my LINQ.

I have a database with id, Name, and pID. For instance, the data would be:

```<code>id=1 | Name='A1' | pID = 0
id=2 | Name='A2' | pID = 0
id=3 | Name='A3' | pID = 0
id=4 | Name='A2' | pID = 5
</code>```

In this case the pID=0 is the defaults data. However, when someone edit a specific Name, a new record is inserted for this name with a new pID. My problem is when I try to query this data. I need to get all the Names for a specific pID and the defaults, but I can't have the same names.
I want a query that return the ids 1, 4, and 3.

I tried it:

```<code>int id = 5;

var test= db.MyTable.Where(a => a.pID == id).ToList();
</code>```

It only returns the row with id=4

```<code>int id = 5;

var test= db.MyTable.Where(a => a.pID == id || a.pID == 0).ToList();
</code>```

It return everything.

Does anyone know how to query it using LINQ?

答:
If I understand your question correctly, you want to distinct Name by considering Pid. You can try like this;

```<code>  int id = 5;
  var records = db.MyTable.Where(x => x.pID == 0 || x.pID == id).OrderByDescending(x => x.pID).GroupBy(x => x.Name)
                .Select(x => x.FirstOrDefault()).ToList();
</code>```

Title: LINQ query multiple conditions

Body:
I need to have multiple conditions in my LINQ.

I have a database with id, Name, and pID. For instance, the data would be:

id=1 | Name='A1' | pID = 0
id=2 | Name='A2' | pID = 0
id=3 | Name='A3' | pID = 0
id=4 | Name='A2' | pID = 5

In this case the pID=0 is the defaults data. However, when someone edit a specific Name, a new record is inserted for this name with a new pID. My problem is when I try to query this data. I need to get all the Names for a specific pID and the defaults, but I can't have the same names.
I want a query that return the ids 1, 4, and 3.

I tried it:

int id = 5;

var test= db.MyTable.Where(a => a.pID == id).ToList();

It only returns the row with id=4

int id = 5;

var test= db.MyTable.Where(a => a.pID == id || a.pID == 0).ToList();

It return everything.

Does anyone know how to query it using LINQ?

Body:
If I understand your question correctly, you want to distinct Name by considering Pid. You can try like this;

  int id = 5;
  var records = db.MyTable.Where(x => x.pID == 0 || x.pID == id).OrderByDescending(x => x.pID).GroupBy(x => x.Name)
                .Select(x => x.FirstOrDefault()).ToList();


问:
Mandelbrot Sequence with Python's Turtle
I am trying to draw the mandelbrot sequence with python's turtle graphics. I am using two classes, one to represent the mandelbrot sequence.

```<code>class Mandelbrot:
def __init__(self,c,limit=50):
    self.__limit = int(limit)
    self.__colormap = ['black','white']
    self.__cardinality = limit
    z = 0
    for i in range(limit):
        z = z * z + c

        if abs(z) > 2:
            self.__cardinality = i
            return

def getColor(self):
    if self.__cardinality == self.__limit:
        return self.__colormap[0]
    return self.__colormap[1]
</code>```

The other class represents the turtle display.

```<code>import turtle
from mandelbrot import *

class Display:
    def __init__(self):
        self.t = turtle.Turtle()
        self.t.ht();self.t.turtlesize(1)
        self.t.speed(0)
        turtle.tracer(2000,0)

    for x in range(-150,151):
        for y in range(-150,151):
            self.t.color(Mandelbrot(turtleConvert(x,y)).getColor())
            self.t.goto(x,y)

def turtleConvert(x,y): #converts from turtle pixels to the complex plane
    return complex((x/300)*4,(y/300)*4)
</code>```

When I make an instance of the display class, the program runs but only prints the lower half of the fractal. Could anyone provide a solution?

This is a picture of my result.

答:
I have the same problem on Linux Mint but I see it draws upper part and later it removes it.

Problem is because goto(x,y) draws white line when turtle moves from top to bottom in next column - ie. from (0, 150) to (1, -150) - and this line removes part of your image.

You have to move it manually without drawing line

```<code>    for x in range(-150,151):
        for y in range(-150,151):
            self.t.color(Mandelbrot(turtleConvert(x,y)).getColor())
            self.t.goto(x,y)

        # move to bottom in next column without creating white line
        self.t.up()
        self.t.goto(x+1, -150)
        self.t.down()
</code>```

Or move it before you start every new column

```<code>    for x in range(-150, 151):
        # move to bottom without creating white line
        self.t.up()
        self.t.goto(x, -150)
        self.t.down()

        for y in range(-150, 151):
            self.t.color(Mandelbrot(turtleConvert(x,y)).getColor())
            self.t.goto(x,y)
</code>```

Body:
I am trying to draw the mandelbrot sequence with python's turtle graphics. I am using two classes, one to represent the mandelbrot sequence.

class Mandelbrot:
def __init__(self,c,limit=50):
    self.__limit = int(limit)
    self.__colormap = ['black','white']
    self.__cardinality = limit
    z = 0
    for i in range(limit):
        z = z * z + c

        if abs(z) > 2:
            self.__cardinality = i
            return

def getColor(self):
    if self.__cardinality == self.__limit:
        return self.__colormap[0]
    return self.__colormap[1]

The other class represents the turtle display.

import turtle
from mandelbrot import *

class Display:
    def __init__(self):
        self.t = turtle.Turtle()
        self.t.ht();self.t.turtlesize(1)
        self.t.speed(0)
        turtle.tracer(2000,0)

    for x in range(-150,151):
        for y in range(-150,151):
            self.t.color(Mandelbrot(turtleConvert(x,y)).getColor())
            self.t.goto(x,y)

def turtleConvert(x,y): #converts from turtle pixels to the complex plane
    return complex((x/300)*4,(y/300)*4)

When I make an instance of the display class, the program runs but only prints the lower half of the fractal. Could anyone provide a solution?

This is a picture of my result.

Body:
I have the same problem on Linux Mint but I see it draws upper part and later it removes it.

Problem is because goto(x,y) draws white line when turtle moves from top to bottom in next column - ie. from (0, 150) to (1, -150) - and this line removes part of your image.

You have to move it manually without drawing line

    for x in range(-150,151):
        for y in range(-150,151):
            self.t.color(Mandelbrot(turtleConvert(x,y)).getColor())
            self.t.goto(x,y)

        # move to bottom in next column without creating white line
        self.t.up()
        self.t.goto(x+1, -150)
        self.t.down()

Or move it before you start every new column

    for x in range(-150, 151):
        # move to bottom without creating white line
        self.t.up()
        self.t.goto(x, -150)
        self.t.down()

        for y in range(-150, 151):
            self.t.color(Mandelbrot(turtleConvert(x,y)).getColor())
            self.t.goto(x,y)


问:
Crystall report with different size footer
I have a complex report printing on pre-print stationary, first page needs a short footer, second page a larger footer, subsequent pages no footer at all. My suppression rules are working fine but the short footer is being incorrectly positioned at the same start point as the larger footer.

In Crystall 11, it appears the footers take their start position from the largest footer regardless of which footer is being displayed/suppressed? Is that really so?

答:
Well, I am too having the same problem.  For days, I tried to find way around this limitation.

If you can manipulate the dataset that feed the report, add a col "PageGroup"; set the value of this col according to your page setting.  For example, the first 20 rows "FirstPage", and the rest of the rows "OtherPages".

In Crystal report use group by section on "PageGroup"; place the 1st page footer in this group by section.  Edit suppress formula for this group section: CurrentPage > 1.

Use the report page footer for other pages; you will need formula to suppress it on the first page.