问:
Error with my python code
I am new to python with great desire to learn the language. However, right now i need someone help with a code i am currently working on which keep flagging this error :
Oops, try again. get_average(alice) returned None instead of the expected 91.15

This is the question with my solution below also:
Write a function called get_average that takes a student dictionary (like lloyd, alice, or tyler) as input and returns his/her weighted average.

Define a function called get_average that takes one argument called student.
Make a variable homework that stores the average() of student["homework"].
Repeat step 2 for "quizzes" and "tests".
Multiply the 3 averages by their weights and return the sum of those three. Homework is 10%, quizzes are 30% and tests are 60%.

MY SOLUTION:

```<code>lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": 88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
 "homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}

# Add your function below!
def average(numbers):
    total = sum(numbers)
    total = float(total)
    result = total/len(numbers)
    return result

def get_average(student):
    homework = average(student["homework"])
    quizzes = average(student["quizzes"])
    tests = average(student["tests"])
    Av = (0.1 * homework) + (0.6 * tests) +(0.3 * quizzes)
    print Av
</code>```

答:
Alternatively, you can also try this: </p>

```<code>import numpy as np
def weighted_average(d):
 """Returns weighted average of values corresponding to keys homework,
    tests & quizzes of a dictionary d"""

    # bind dict keys to variables homework, test, quiz
    homework, test, quiz = [d["homework"]], [d["tests"]], [d["quizzes"]]
    # calculate average through np.mean() and Return the value
    return "Average: {}".format((0.1 * np.mean(homework)) + (0.6 * np.mean(test)) + (0.3 * np.mean(quiz)))

d = lloyd = {"name": "Lloyd","homework": [90.0, 97.0, 75.0, 92.0],"quizzes": [88.0, 40.0, 94.0],"tests": [75.0, 90.0]}
averages(d)

>>>'Average: 80.55'
</code>```

Title: Error with my python code

Body:
I am new to python with great desire to learn the language. However, right now i need someone help with a code i am currently working on which keep flagging this error :
Oops, try again. get_average(alice) returned None instead of the expected 91.15

This is the question with my solution below also:
Write a function called get_average that takes a student dictionary (like lloyd, alice, or tyler) as input and returns his/her weighted average.

Define a function called get_average that takes one argument called student.
Make a variable homework that stores the average() of student["homework"].
Repeat step 2 for "quizzes" and "tests".
Multiply the 3 averages by their weights and return the sum of those three. Homework is 10%, quizzes are 30% and tests are 60%.

MY SOLUTION:

lloyd = {
"name": "Lloyd",
"homework": [90.0, 97.0, 75.0, 92.0],
"quizzes": 88.0, 40.0, 94.0],
"tests": [75.0, 90.0]
}
alice = {
"name": "Alice",
"homework": [100.0, 92.0, 98.0, 100.0],
"quizzes": [82.0, 83.0, 91.0],
"tests": [89.0, 97.0]
}
tyler = {
"name": "Tyler",
 "homework": [0.0, 87.0, 75.0, 22.0],
"quizzes": [0.0, 75.0, 78.0],
"tests": [100.0, 100.0]
}

# Add your function below!
def average(numbers):
    total = sum(numbers)
    total = float(total)
    result = total/len(numbers)
    return result

def get_average(student):
    homework = average(student["homework"])
    quizzes = average(student["quizzes"])
    tests = average(student["tests"])
    Av = (0.1 * homework) + (0.6 * tests) +(0.3 * quizzes)
    print Av

Body:
Alternatively, you can also try this:

import numpy as np
def weighted_average(d):
 """Returns weighted average of values corresponding to keys homework,
    tests & quizzes of a dictionary d"""

    # bind dict keys to variables homework, test, quiz
    homework, test, quiz = [d["homework"]], [d["tests"]], [d["quizzes"]]
    # calculate average through np.mean() and Return the value
    return "Average: {}".format((0.1 * np.mean(homework)) + (0.6 * np.mean(test)) + (0.3 * np.mean(quiz)))

d = lloyd = {"name": "Lloyd","homework": [90.0, 97.0, 75.0, 92.0],"quizzes": [88.0, 40.0, 94.0],"tests": [75.0, 90.0]}
averages(d)

>>>'Average: 80.55'


来源: stackexchange

问:
How to delete only selected rows from DB after printed them in foreach loop
I'm wondering how I can delete selected (with checkbox) rows from a database that were printed using the foreach loop.
For now I only have this:</p>

```<code> if(isset($_POST['submitS1'])) {
        $myads = $wpdb->get_results( "SELECT * FROM ads ORDER BY id DESC");
        foreach ($myads as $pointer2) {
            $id_ad = $pointer2->id;
          $title = $pointer2->title;
          $text1 = $pointer2->text1;
          $nme = $pointer2->name;
          echo '<br><h2>Message:</h2>'.$text1.'';
          echo '<br><h2>Title:</h2>'.$title.'<br>';
          echo '<br><h2>Name:</h2>'.$name.'<br>';
         echo ' <form method="post"><input type="checkbox" name="accept" value="accepto">Delete this ad<br>
        </form>';

        }
 echo '<form method="post">
    <input type="submit" name="submito" value="Delete selected ads">
        </form>';
        if(isset($_POST['submito'], $_POST['accept'])) {
        $sql2 ="DELETE FROM `mydb`.`ads` WHERE `ads`.`id` = ".$id_ad."";
        $wpdb->query($sql2);
        }

        }
</code>```

答:
Use only one form.

Set your checkbox names to be "delete_ids[$id]"

```<code><input type="checkbox" name="delete_ids[<?php echo $id;?>]" />
</code>```

PHP will process the POST data and give you a neat POST variable called delete_ids which contains an array of the ids you need to delete (as keys). Iterate over it... and delete.

```<code>$ids = array_keys( $_POST["delete_ids"] );
if(count( $ids ))
{
    var_dump( $ids );
    $ids = implode( ",", array_map( intval, $ids ));
    $sql = "DELETE FROM... WHERE id IN ($ids)";
    .....
</code>```

Simple as that.

ContentLicense: CC BY-SA 3.0

Body:
I'm wondering how I can delete selected (with checkbox) rows from a database that were printed using the foreach loop.
For now I only have this:

 if(isset($_POST['submitS1'])) {
        $myads = $wpdb->get_results( "SELECT * FROM ads ORDER BY id DESC");
        foreach ($myads as $pointer2) {
            $id_ad = $pointer2->id;
          $title = $pointer2->title;
          $text1 = $pointer2->text1;
          $nme = $pointer2->name;
          echo '

Message:
'.$text1.'';
          echo '

Title:
'.$title.'
';
          echo '

Name:
'.$name.'
';
         echo ' <form method="post"><input type="checkbox" name="accept" value="accepto">Delete this ad

        </form>';

        }
 echo '<form method="post">
    <input type="submit" name="submito" value="Delete selected ads">
        </form>';
        if(isset($_POST['submito'], $_POST['accept'])) {
        $sql2 ="DELETE FROM `mydb`.`ads` WHERE `ads`.`id` = ".$id_ad."";
        $wpdb->query($sql2);
        }

        }

Body:
Use only one form.

Set your checkbox names to be "delete_ids[$id]"

<input type="checkbox" name="delete_ids[<?php echo $id;?>]" />

PHP will process the POST data and give you a neat POST variable called delete_ids which contains an array of the ids you need to delete (as keys). Iterate over it... and delete.

$ids = array_keys( $_POST["delete_ids"] );
if(count( $ids ))
{
    var_dump( $ids );
    $ids = implode( ",", array_map( intval, $ids ));
    $sql = "DELETE FROM... WHERE id IN ($ids)";
    .....

Simple as that.


问:
Laravel faker generate gender from name
What is the optimum way of generating gender using faker, having generated a name so that the gender matches the name </p>

```<code> return [
    'name' => $faker->name,
    'email' => $faker->safeEmail,
    'username' => $faker->userName,
    'phone' => $faker->phoneNumber,
    'gender' => $faker->randomElement(['male', 'female']),//the gender does not match the name as it is.
    'address' => $faker->address,
    'dob' => $faker->date($format = 'Y-m-d', $max = 'now'),
    'password' => bcrypt('secret')
    ];
</code>```

答:
Looking at the documentation and an issue raised on the their Github issues section, your solution seems to be the best. Some methods allow you to specify the gender for a name so you could do like this:

```<code>$gender = $faker->randomElement(['male', 'female']);

return [
    'name' => $faker->name($gender),
    'email' => $faker->safeEmail,
    'username' => $faker->userName,
    'phone' => $faker->phoneNumber,
    'gender' => $gender,
    'address' => $faker->address,
    'dob' => $faker->date($format = 'Y-m-d', $max = 'now'),
    'password' => bcrypt('secret')
];
</code>```

Hopefully this fits your requirement.

Title: Laravel faker generate gender from name

Body:
What is the optimum way of generating gender using faker, having generated a name so that the gender matches the name

 return [
    'name' => $faker->name,
    'email' => $faker->safeEmail,
    'username' => $faker->userName,
    'phone' => $faker->phoneNumber,
    'gender' => $faker->randomElement(['male', 'female']),//the gender does not match the name as it is.
    'address' => $faker->address,
    'dob' => $faker->date($format = 'Y-m-d', $max = 'now'),
    'password' => bcrypt('secret')
    ];

Body:
Looking at the documentation and an issue raised on the their Github issues section, your solution seems to be the best. Some methods allow you to specify the gender for a name so you could do like this:

$gender = $faker->randomElement(['male', 'female']);

return [
    'name' => $faker->name($gender),
    'email' => $faker->safeEmail,
    'username' => $faker->userName,
    'phone' => $faker->phoneNumber,
    'gender' => $gender,
    'address' => $faker->address,
    'dob' => $faker->date($format = 'Y-m-d', $max = 'now'),
    'password' => bcrypt('secret')
];

Hopefully this fits your requirement.

ContentLicense: CC BY-SA 4.0


问:
is it possible to print an image with node.js?
Ok, so I'm trying to print from a webpage (the typical "print" button, but I don't want the print dialog to appear) so I decided to use my already existing node.js backend to do the task (mainly because printing from browser is nearly impossible without the printing dialog).

I found the node-printer (https://github.com/tojocky/node-printer) module, and it works great, but only with text. I tried to send RAW data, but what it does is printing the raw characters. What I actually need is to print a logo, along with some turn information (this is for a customer care facility).

Also, the printer must be installed locally, so I can't use IPP.

Is there any way to print an image, or a combination of images and text with node.js? can it be done through node-printer or is there another way?

答:
I had success with the Node IPP package https://www.npmjs.com/package/ipp.

The example code on the docs, which uses another node module PDFKIT to convert  your html/file into a PDF, does not work. See my answer here: Cannot print with node js ipp module for a working example.


问:
Any better approach for layout design?
just wondering if anyone else has a better suggestion that what I'm coming up with.

The issue is to do with a TabLayout, 5 Tabs all using a single Activity.  Each Tab layout contains quite a few fields so the main parent on each tab is a ScrollView.

What I currently have is a 'Save' & 'Cancel' button sitting outside the scrollviews so theyre always visible and there for the user regardless which tab they're on.  The problem is that since I'm using Tabs and always have these buttons visible when they are editing and the IME is displayed, they'res barely any of the form visible.

So I think the best thing for me to do is to probably show the buttons at the end of each scrollview.  What I don't like about this is as I have 5 tabs, it will mean I have to declare 5 sets of the buttons, and of course define them and bind them in the Activity.. which seems rather messy and inefficient.

So if anyone has any better ideas I sure would love to hear them :-)

Thanks

Rgds,

Dave

答:
Some of the options you got is

Try to put a title bar, and move the save and cancel buttons there (Small image buttons).

Save can be moved to the menu too (not recommended).

Auto Save functionality can also help, depends on how useful is it to you.

Try to use custom images for tabs, and make it take less space.

else, remove the save and cancel buttons, after the user makes any modifications, and presses back, prompt him to save the unsaved changes.

ContentLicense: CC BY-SA 2.5

Title: Any better approach for layout design?


问:
c++ paste value and print string
I declare 2 string type strings, qhich is s, s1. I use s string with 'cin'
and I paste 3 values in s1. Then I print with 'cout' but it can't print string.

Here is my code

```<code>#include<iostream>
#include<cstdio>
using namespace std;

int main()

{

    string s,s1;
    cin>>s;
    s1[0]=s[1];
    s1[1]=s[2];
    s1[2]=s[3];
    s1[3]='\0';
    cout<<s1<<endl;
    return 0;
}
</code>```

s1 was not empty.... cout<<s1[0]<<s1[1]<<s1[2] and see.
Why s1 can't print?

答:
String assignment cannot be done by assigning indexes without fixing or defining the size of the string. It may cause a string subscript error. If you want to do this, I think string concatenation is the best method; that is, by adding substrings or string indexes into string. I've given some code below that uses the string concatenation method.</p>

```<code>#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
int main()
{
    string s,s1="";
    cin>>s;
    s1= s1 + s[1];
    s1= s1 + s[2];
    s1= s1 + s[3];
    cout<<s1<<endl;
    return 0;
}
</code>```

Title: c++ paste value and print string

Body:
I declare 2 string type strings, qhich is s, s1. I use s string with 'cin'
and I paste 3 values in s1. Then I print with 'cout' but it can't print string.

Here is my code

#include<iostream>
#include<cstdio>
using namespace std;

int main()

{

    string s,s1;
    cin>>s;
    s1[0]=s[1];
    s1[1]=s[2];
    s1[2]=s[3];
    s1[3]='\0';
    cout<<s1<<endl;
    return 0;
}

s1 was not empty.... cout<<s1[0]<<s1[1]<<s1[2] and see.
Why s1 can't print?

Body:
String assignment cannot be done by assigning indexes without fixing or defining the size of the string. It may cause a string subscript error. If you want to do this, I think string concatenation is the best method; that is, by adding substrings or string indexes into string. I've given some code below that uses the string concatenation method.

#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
int main()
{
    string s,s1="";
    cin>>s;
    s1= s1 + s[1];
    s1= s1 + s[2];
    s1= s1 + s[3];
    cout<<s1<<endl;
    return 0;
}


问:
Rails 4 - why turbolinks causes datepicker stopping working
We upgraded to Rails 4.2 from Rails 3.2 and datepicker (jquery ui) stops working after upgrading. Bootstrap 3 was also used in both Rails 3/4.

Here is an example of datepicker field in simple_form:

```<code><%= f.input :since_date, :label => t('Since'), :as => :string %>
</code>```

After removing the turbolinks from app's application.js, datepicker starts working again. Can someone explain why turbolinks causes the problem.

答:
You need to handle the turbo links load event and destroy and re-initialize any date pickers.</p>

```<code>// Called when page first loads.
$(function(){
  $('.date-picker').datepicker();
});

// Handle turbolinks page load.
$( document ).on('turbolinks:load', function() {
  $('.hasDatepicker').datepicker("destroy");
  $('.date-picker').datepicker();
});
</code>```

Body:
We upgraded to Rails 4.2 from Rails 3.2 and datepicker (jquery ui) stops working after upgrading. Bootstrap 3 was also used in both Rails 3/4.

Here is an example of datepicker field in simple_form:

<%= f.input :since_date, :label => t('Since'), :as => :string %>

After removing the turbolinks from app's application.js, datepicker starts working again. Can someone explain why turbolinks causes the problem.

Body:
You need to handle the turbo links load event and destroy and re-initialize any date pickers.

// Called when page first loads.
$(function(){
  $('.date-picker').datepicker();
});

// Handle turbolinks page load.
$( document ).on('turbolinks:load', function() {
  $('.hasDatepicker').datepicker("destroy");
  $('.date-picker').datepicker();
});


问:
How to view this custom option in another phtml file in Magento2?
which way we have to override this position in custom option to view in another phtml file.

added this code in checkout_cart_index.xml which is override only the form.phtml not override the default.phtml file.

```<code>  <?xml version="1.0"?>
  <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<!-- <update handle="checkout_cart_item_renderers"/> -->
<body>
    <referenceContainer name="content">
        <referenceBlock name="checkout.cart.form">
            <action method="setTemplate">
                <argument name="template" xsi:type="string">Bespoke_Bespoke::cart/form.phtml</argument>
            </action>
    </referenceBlock>
     <referenceBlock name="checkout.cart.item.renderers.override">
    <action method="setTemplate">
        <argument name="template" xsi:type="string">Bespoke_Bespoke::cart/item/default.phtml</argument>
    </action>
</referenceBlock>
    </referenceContainer>
</body>
</code>```

i am getting error regarding the 'checkout.cart.item.renderers' already has a child with alias 'simple' i have modify that file of checkout_cart_item_renderer.xml

```<code> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<!-- <update handle="checkout_item_price_renderers"/> -->
<body>
  <referenceBlock name="checkout.cart.form">
<action method="setOverriddenTemplates">
    <argument xsi:type="array">
        <!-- list override templates -->
        <item name="default" xsi:type="string">Bespoke_Bespoke::cart/item/default.phtml</item>
        <item name="simple" xsi:type="string">Bespoke_Bespoke::cart/item/default.phtml</item>
        <item name="virtual" xsi:type="string">Bespoke_Bespoke::cart/item/default.phtml</item>
    </argument>
  </action>
  </referenceBlock>
</body>
</page>
</code>```

to override the file we use to etc/di.xml

```<code> <config  xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
   <preference for="Magento\Checkout\Block\Cart\AbstractCart" type="AGS\Bespoke\Block\Checkout\Cart\AbstractCart"/><preference for="Magento\Catalog\Block\Product\View\Option" type="AGS\Bespoke\Block\Product\View\Option"/>
   <preference for=" Magento\Checkout\Block\Cart" type="AGS\Bespoke\Block\Checkout\Cart"/>
   <preference for="\Magento\Checkout\Block\Cart\Item\Renderer" type="AGS\Bespoke\Block\Checkout\Cart\Item\Renderer"/>
   <virtualType name="AGS\Bespoke\Model\ResourceModel\Bespoke\Bespoke\Collection" type="Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult">
  <arguments><argument name="mainTable" xsi:type="string">ags_bespoke</argument><argument name="resourceModel" xsi:type="string">AGS\Bespoke\Model\ResourceModel\Bespoke</argument>

  </arguments></virtualType><type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
<arguments><argument name="collections" xsi:type="array">
<item name="bespoke_record_bespoke_list_data_source" xsi:type="string">AGS\Bespoke\Model\ResourceModel\Bespoke\Bespoke\Collection</item>
</code>```

答:
The way the attributes displayed in the product view pay may vary a lot from theme to theme.

But if you are using a theme similar to the default theme (before 1.9) here is what you can do.

Look for this in the catalog.xml of your theme:

```<code><block type="catalog/product_view_attributes" name="product.attributes" as="additional" template="catalog/product/view/attributes.phtml">
    <action method="addToParentGroup"><group>detailed_info</group></action>
</block>
</code>```

and remove the line <action method="addToParentGroup"><group>detailed_info</group></action>. That's the line responsible for placing the block in a specific group.

Then edit catalog/product/view.phtml and add this line where you want the attributes to be displayed.

```<code><?php echo $this->getChildHtml('additional')?>
</code>```

If you are using a theme similar to the rwd theme (the 1.9 default one) you should do this:

```<code><block type="catalog/product_view_attributes" name="product.attributes" as="additional" template="catalog/product/view/attributes.phtml">
    <action method="addToParentGroup"><group>detailed_info</group></action>
    <action method="setTitle" translate="value"><value>Additional Information</value></action>
</block>
</code>```

You should to the same thing as above. But in addition also remove this line

```<code><action method="setTitle" translate="value"><value>Additional Information</value></action>
</code>```

Body:
which way we have to override this position in custom option to view in another phtml file.

added this code in checkout_cart_index.xml which is override only the form.phtml not override the default.phtml file.

  <?xml version="1.0"?>
  <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

    <referenceContainer name="content">
        <referenceBlock name="checkout.cart.form">
            <action method="setTemplate">
                <argument name="template" xsi:type="string">Bespoke_Bespoke::cart/form.phtml</argument>
            </action>
    </referenceBlock>
     <referenceBlock name="checkout.cart.item.renderers.override">
    <action method="setTemplate">
        <argument name="template" xsi:type="string">Bespoke_Bespoke::cart/item/default.phtml</argument>
    </action>
</referenceBlock>
    </referenceContainer>

i am getting error regarding the 'checkout.cart.item.renderers' already has a child with alias 'simple' i have modify that file of checkout_cart_item_renderer.xml

 <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

  <referenceBlock name="checkout.cart.form">
<action method="setOverriddenTemplates">
    <argument xsi:type="array">

        <item name="default" xsi:type="string">Bespoke_Bespoke::cart/item/default.phtml</item>
        <item name="simple" xsi:type="string">Bespoke_Bespoke::cart/item/default.phtml</item>
        <item name="virtual" xsi:type="string">Bespoke_Bespoke::cart/item/default.phtml</item>
    </argument>
  </action>
  </referenceBlock>

</page>

to override the file we use to etc/di.xml

 <config  xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
   <preference for="Magento\Checkout\Block\Cart\AbstractCart" type="AGS\Bespoke\Block\Checkout\Cart\AbstractCart"/><preference for="Magento\Catalog\Block\Product\View\Option" type="AGS\Bespoke\Block\Product\View\Option"/>
   <preference for=" Magento\Checkout\Block\Cart" type="AGS\Bespoke\Block\Checkout\Cart"/>
   <preference for="\Magento\Checkout\Block\Cart\Item\Renderer" type="AGS\Bespoke\Block\Checkout\Cart\Item\Renderer"/>
   <virtualType name="AGS\Bespoke\Model\ResourceModel\Bespoke\Bespoke\Collection" type="Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult">
  <arguments><argument name="mainTable" xsi:type="string">ags_bespoke</argument><argument name="resourceModel" xsi:type="string">AGS\Bespoke\Model\ResourceModel\Bespoke</argument>

  </arguments></virtualType><type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
<arguments><argument name="collections" xsi:type="array">
<item name="bespoke_record_bespoke_list_data_source" xsi:type="string">AGS\Bespoke\Model\ResourceModel\Bespoke\Bespoke\Collection</item>

Body:
The way the attributes displayed in the product view pay may vary a lot from theme to theme.

But if you are using a theme similar to the default theme (before 1.9) here is what you can do.

Look for this in the catalog.xml of your theme:

<block type="catalog/product_view_attributes" name="product.attributes" as="additional" template="catalog/product/view/attributes.phtml">
    <action method="addToParentGroup"><group>detailed_info</group></action>
</block>

and remove the line <action method="addToParentGroup"><group>detailed_info</group></action>. That's the line responsible for placing the block in a specific group.

Then edit catalog/product/view.phtml and add this line where you want the attributes to be displayed.

<?php echo $this->getChildHtml('additional')?>

If you are using a theme similar to the rwd theme (the 1.9 default one) you should do this:

<block type="catalog/product_view_attributes" name="product.attributes" as="additional" template="catalog/product/view/attributes.phtml">
    <action method="addToParentGroup"><group>detailed_info</group></action>
    <action method="setTitle" translate="value"><value>Additional Information</value></action>
</block>

You should to the same thing as above. But in addition also remove this line

<action method="setTitle" translate="value"><value>Additional Information</value></action>


问:
How to get substring out of String in java?
i am getting this String input="One Two Three";
how to get substrings out of it?
I want to get optimized solutions.
help me!</p>

答:
Use Split in java</p>

```<code>String input="one two three";
String[] output=input.split(" ");
System.out.println(output[0]);
System.out.println(output[1]);
System.out.println(output[2]);
</code>```

Body:
Use Split in java

String input="one two three";
String[] output=input.split(" ");
System.out.println(output[0]);
System.out.println(output[1]);
System.out.println(output[2]);


问:
top position of text spread across two columns
I'm having problem with setting top position for the text.
There is main div with "column-count:2" and inside there is some text which spreads in two columns.
Text is in divided in different tags call "sen". There is also some text which is highlighted with some class.
Now I need to find top position of highlighted text which is spread across both the columns
But it is giving me wrong position value, i.e. top position in second column i.e. 0

Here is the fiddle link to get the clear idea:
https://jsfiddle.net/trupti11/1gt0bf54/

$(function() {
  //This gives top as 0 even though some part of class "h45" is at bottom
  console.log("position sen tag with class h45 " + $('.h45').position().top);

  //This gives correct position of class "span_1892"
  console.log("position span " + $('.span_1892').position().top);

  //problem here: This gives wrong position of class "span_1893" which needs to be something 65px
  console.log("position span " + $('.span_1893').position().top);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.textBox {
  width: 500px;
  height: 200px;
  column-count: 2;
  margin: 0;
  padding: 0;
  position: relative;
}

span {
  background-color: #ff0;
  padding: 0;
  margin: 0;
}</code>```

  <sen name="44" class="h h44">
    Barnitz erwiderte seinen Gruß und verharrte einen Moment lang in dieser Pose, als erwarte er, für ein Propagandaplakat fotografiert zu werden.</sen>
  <sen name="45" class="h h45"> Es wäre nicht das erste Mal gewesen, denn so hochgewachsen, kräftig und blond wie er war, verkörperte er das arische Ideal.</sen>

```

答:
Probably, the easiest way to accomplish this is to add the height of column one to the position that you find in column two:

function getPosition(target){
  var col = target.closest("sen");
  var h_span = 0;
  //Loop through all "sen" items
  $.each($("sen"), function(i, val){
    //Exit when found the "sen" contains my target
    if(!$(val).find(target).length){
      h_span += $(val).height();
    }else{
      return;
    }
  });
  return text_pos = h_span + target.position().top;
}

var target = $('.span_1893');
console.log("position span is "+ getPosition(target));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.textBox {
  width: 500px;
  height: 200px;
  column-count: 2;
  margin:0;
  padding:0;
  position:relative;
}

span {
  background-color:#ff0;
  padding:0;
  margin:0;
}</code>```

<sen name="44" class="h h44">
Barnitz erwiderte seinen Gruß und verharrte einen Moment lang in dieser Pose, als erwarte er, für ein Propagandaplakat fotografiert zu werden.</sen>
<sen name="45" class="h h45"> Es wäre nicht das erste Mal gewesen, denn so hochgewachsen, kräftig und blond wie er war, verkörperte er das arische Ideal.</sen>

```

I hope it helps you. Bye

Body:
I'm having problem with setting top position for the text.
There is main div with "column-count:2" and inside there is some text which spreads in two columns.
Text is in divided in different tags call "sen". There is also some text which is highlighted with some class.
Now I need to find top position of highlighted text which is spread across both the columns
But it is giving me wrong position value, i.e. top position in second column i.e. 0

Here is the fiddle link to get the clear idea:
https://jsfiddle.net/trupti11/1gt0bf54/

$(function() {
  //This gives top as 0 even though some part of class "h45" is at bottom
  console.log("position sen tag with class h45 " + $('.h45').position().top);

  //This gives correct position of class "span_1892"
  console.log("position span " + $('.span_1892').position().top);

  //problem here: This gives wrong position of class "span_1893" which needs to be something 65px
  console.log("position span " + $('.span_1893').position().top);
});

.textBox {
  width: 500px;
  height: 200px;
  column-count: 2;
  margin: 0;
  padding: 0;
  position: relative;
}

span {
  background-color: #ff0;
  padding: 0;
  margin: 0;
}

  <sen name="44" class="h h44">
    Barnitz erwiderte seinen Gruß und verharrte einen Moment lang in dieser Pose, als erwarte er, für ein Propagandaplakat fotografiert zu werden.</sen>
  <sen name="45" class="h h45"> Es wäre nicht das erste Mal gewesen, denn so hochgewachsen, kräftig und blond wie er war, verkörperte er das arische Ideal.</sen>

Body:
Probably, the easiest way to accomplish this is to add the height of column one to the position that you find in column two:

function getPosition(target){
  var col = target.closest("sen");
  var h_span = 0;
  //Loop through all "sen" items
  $.each($("sen"), function(i, val){
    //Exit when found the "sen" contains my target
    if(!$(val).find(target).length){
      h_span += $(val).height();
    }else{
      return;
    }
  });
  return text_pos = h_span + target.position().top;
}

var target = $('.span_1893');
console.log("position span is "+ getPosition(target));

.textBox {
  width: 500px;
  height: 200px;
  column-count: 2;
  margin:0;
  padding:0;
  position:relative;
}

span {
  background-color:#ff0;
  padding:0;
  margin:0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="textBox">
<sen name="44" class="h h44">
Barnitz erwiderte seinen Gruß und verharrte einen Moment lang in dieser Pose, als erwarte er, für ein Propagandaplakat <span class="span_1892">fotografiert</span> zu werden.</sen>
<sen name="45" class="h h45"> Es wäre nicht das <span class="span_1893">erste Mal gewesen, denn</span> so hochgewachsen, kräftig und blond wie er war, verkörperte er das arische Ideal.</sen>
</div>

I hope it helps you. Bye


问:
more than one caption with featherlight?
i am using featherlight.js for image galleries and used this code for captions:

```<code>$.featherlightGallery.prototype.afterContent = function() {
  var caption = this.$currentTarget.find('img').attr('alt');
  this.$instance.find('.caption').remove();
  $('<div class="caption">').text(caption).appendTo(this.$instance.find('.featherlight-content'));
};
</code>```

now a client wants to add a second caption which contains only copyright-information on the right side of gallery-images. is it possible to have two captions, one named .caption and the second maybe .copyright?

I already tried with "data-caption=" and a simple copy of the above js-initial but it failed.

any ideas?
thank you in advance and merry christmas!

答:
You could use a data attribute.

```<code>$.featherlightGallery.prototype.afterContent = function() {
  var caption = this.$currentTarget.find('img').attr('alt');
  this.$instance.find('.caption').remove();
  $('<div class="caption">').text(caption).appendTo(this.$instance.find('.featherlight-content'));

  var copyright = this.$currentTarget.find('img').data('copyright');
  this.$instance.find('.copyright').remove();
  $('<div class="copyright">').text(copyright).appendTo(this.$instance.find('.featherlight-content'));
};
</code>```

Then in your markup add

```<code><img src="..." alt="my caption text" data-copyright="my copyright text">
</code>```

and in your css

```<code>.copyright {
  float: right;
}
</code>```

or something to suit.

If you need it to be conditional you can check for the defined-ness and/or length of the data-copyright attribute.

Body:
i am using featherlight.js for image galleries and used this code for captions:

$.featherlightGallery.prototype.afterContent = function() {
  var caption = this.$currentTarget.find('img').attr('alt');
  this.$instance.find('.caption').remove();
  $('
').text(caption).appendTo(this.$instance.find('.featherlight-content'));
};

now a client wants to add a second caption which contains only copyright-information on the right side of gallery-images. is it possible to have two captions, one named .caption and the second maybe .copyright?

I already tried with "data-caption=" and a simple copy of the above js-initial but it failed.

any ideas?
thank you in advance and merry christmas!

Body:
You could use a data attribute.

$.featherlightGallery.prototype.afterContent = function() {
  var caption = this.$currentTarget.find('img').attr('alt');
  this.$instance.find('.caption').remove();
  $('<div class="caption">').text(caption).appendTo(this.$instance.find('.featherlight-content'));

  var copyright = this.$currentTarget.find('img').data('copyright');
  this.$instance.find('.copyright').remove();
  $('<div class="copyright">').text(copyright).appendTo(this.$instance.find('.featherlight-content'));
};

Then in your markup add

<img src="..." alt="my caption text" data-copyright="my copyright text">

and in your css

.copyright {
  float: right;
}

or something to suit.

If you need it to be conditional you can check for the defined-ness and/or length of the data-copyright attribute.


问:
Setting background color for UIAlertController in Swift
I am using the new UIAlertController to implement an options menu of sorts for my application. I am trying to get the background color of the UIAlertController to match the theme of the rest of my application. The theme for my application is pretty simple, and consists of white text with a blue/grey background color for the toolbar and navigation bar, shown below:

However, I am having some trouble trying to get my UIAlertController to conform to this theme. I made the the following two calls to set the text and background color:

```<code>uiAlertController.view.backgroundColor = UIColor(red: CGFloat(.17255), green: CGFloat(.24314), blue: CGFloat(.31373), alpha: CGFloat(1.0))
uiAlertController.view.tintColor = UIColor.whiteColor()
</code>```

This changed the UIAlertController to look like below:

The text was changed from the default blue system color to white, but the background color is not correct. I also tried modifying the specifying opacity (uiAlertController.view.opaque = true) but this did not help either. How do I go about setting the background color so it matches my navigation bar and toolbar? Thanks

答:
for Swift 3 Xcode 8.2.1

```<code>let subview = (alert.view.subviews.first?.subviews.first?.subviews.first!)! as UIView

                subview.backgroundColor = UIColor(red: (145/255.0), green: (200/255.0), blue: (0/255.0), alpha: 1.0)

                alert.view.tintColor = UIColor.black
</code>```

Body:
I am using the new UIAlertController to implement an options menu of sorts for my application. I am trying to get the background color of the UIAlertController to match the theme of the rest of my application. The theme for my application is pretty simple, and consists of white text with a blue/grey background color for the toolbar and navigation bar, shown below:

However, I am having some trouble trying to get my UIAlertController to conform to this theme. I made the the following two calls to set the text and background color:

uiAlertController.view.backgroundColor = UIColor(red: CGFloat(.17255), green: CGFloat(.24314), blue: CGFloat(.31373), alpha: CGFloat(1.0))
uiAlertController.view.tintColor = UIColor.whiteColor()

This changed the UIAlertController to look like below:

The text was changed from the default blue system color to white, but the background color is not correct. I also tried modifying the specifying opacity (uiAlertController.view.opaque = true) but this did not help either. How do I go about setting the background color so it matches my navigation bar and toolbar? Thanks

Body:
for Swift 3 Xcode 8.2.1

let subview = (alert.view.subviews.first?.subviews.first?.subviews.first!)! as UIView

                subview.backgroundColor = UIColor(red: (145/255.0), green: (200/255.0), blue: (0/255.0), alpha: 1.0)

                alert.view.tintColor = UIColor.black


问:
Email Address Validation for ASP.NET
What do you use to validate an email address on a ASP.NET form. I want to make sure that it contains no XSS exploits.

This is ASP.NET 1.1

答:
You should always do server side validaton as well.

```<code>public bool IsValidEmailAddress(string email)
{
    try
    {
        var emailChecked = new System.Net.Mail.MailAddress(email);
        return true;
    }
    catch
    {
        return false;
    }
}
</code>```

UPDATE

You can also use the EmailAddressAttribute in System.ComponentModel.DataAnnotations. Then there is no need for a try-catch to it's a cleaner solution.

```<code>public bool IsValidEmailAddress(string email)
{
    if (!string.IsNullOrEmpty(email) && new EmailAddressAttribute().IsValid(email))
        return true;
    else
        return false;
}
</code>```

Note that the IsNullOrEmpty check is also needed otherwise a null value will return true.

OwnerDisplayName: Brian G

Title: Email Address Validation for ASP.NET

LastEditorDisplayName: Adam Bellaire

Body:
You should always do server side validaton as well.

public bool IsValidEmailAddress(string email)
{
    try
    {
        var emailChecked = new System.Net.Mail.MailAddress(email);
        return true;
    }
    catch
    {
        return false;
    }
}

UPDATE

You can also use the EmailAddressAttribute in System.ComponentModel.DataAnnotations. Then there is no need for a try-catch to it's a cleaner solution.

public bool IsValidEmailAddress(string email)
{
    if (!string.IsNullOrEmpty(email) && new EmailAddressAttribute().IsValid(email))
        return true;
    else
        return false;
}

Note that the IsNullOrEmpty check is also needed otherwise a null value will return true.


问:
Complex query Laravel
Hi I have a complex queries

```<code>SELECT distinct libelle_adresse from adresse
where id_adresse in (select id_adresse from zone_adresse
where fk_zone in (select id_zone from zone
where id_arrondissement in (select id_arrondissement from arrondissement
where libelle_arrondissement="'.$_GET['arrondis'].'")))
</code>```

I've used $arrondis = $request->input('arrondis');to get the "arrondis" parameter from URL and pass it to my Controller.

This my attempt

```<code>    $term = $request->term;

    $arrondis = $request->input('arrondis');

    $query1 = DB::table('arrondissement')
    ->select('id_arrondissement')
    ->where('libelle_arrondissement','=',$arrondis)
    ->get();

    $query2 = DB::table('zone');
    ->select('id_zone')
    ->where('id_arrondissement','=',$query1)
    ->get();

    $query3 = DB::table('zone_adresse');
    ->select('id_adresse')
    ->where('fk_zone','=',$query2)
    ->get();

    $queries = DB::table('adresse');
    ->where('id_adresse','=',$query3)
    ->where('libelle_adresse','like','%'.$term.'%')
    ->take(3)->get();
    foreach ($queries as $query)
    {
        $results[] = ['id' => $query->id_adresse, 'value' => $query->libelle_adresse];
    }
    return response()->json($results);
</code>```

I know that I get the error when I pass the "query(1/2/3) variable" in "where" but I couldn't find any solution

Any help would be appreciated. Thanks

答:
I think the query you are showing if far more complex than what you need.

```<code>SELECT distinct libelle_adresse
FROM adresse as a
INNER JOIN zone_address as za ON a.id_adresse = za.id_adress
INNER JOIN zone as z ON za.fk_zone = z.id_zone
INNER JOIN arrondissement as arr ON arr.id_arrondissement = z.id_arrondissement
Where libelle_arrondissement="'.$_GET['arrondis'].'")))
</code>```

Since i don't have the table structure detail i might have make mistake in the labels i used in front of field. But this request is doing the same and is easier to handle.

Since documentation on laravel join is quite full of example. I hope this will be enough to help you.

Title: Complex query Laravel

Body:
Hi I have a complex queries

SELECT distinct libelle_adresse from adresse
where id_adresse in (select id_adresse from zone_adresse
where fk_zone in (select id_zone from zone
where id_arrondissement in (select id_arrondissement from arrondissement
where libelle_arrondissement="'.$_GET['arrondis'].'")))

I've used $arrondis = $request->input('arrondis');to get the "arrondis" parameter from URL and pass it to my Controller.

This my attempt

    $term = $request->term;

    $arrondis = $request->input('arrondis');

    $query1 = DB::table('arrondissement')
    ->select('id_arrondissement')
    ->where('libelle_arrondissement','=',$arrondis)
    ->get();

    $query2 = DB::table('zone');
    ->select('id_zone')
    ->where('id_arrondissement','=',$query1)
    ->get();

    $query3 = DB::table('zone_adresse');
    ->select('id_adresse')
    ->where('fk_zone','=',$query2)
    ->get();

    $queries = DB::table('adresse');
    ->where('id_adresse','=',$query3)
    ->where('libelle_adresse','like','%'.$term.'%')
    ->take(3)->get();
    foreach ($queries as $query)
    {
        $results[] = ['id' => $query->id_adresse, 'value' => $query->libelle_adresse];
    }
    return response()->json($results);

I know that I get the error when I pass the "query(1/2/3) variable" in "where" but I couldn't find any solution

Any help would be appreciated. Thanks

Body:
I think the query you are showing if far more complex than what you need.

SELECT distinct libelle_adresse
FROM adresse as a
INNER JOIN zone_address as za ON a.id_adresse = za.id_adress
INNER JOIN zone as z ON za.fk_zone = z.id_zone
INNER JOIN arrondissement as arr ON arr.id_arrondissement = z.id_arrondissement
Where libelle_arrondissement="'.$_GET['arrondis'].'")))

Since i don't have the table structure detail i might have make mistake in the labels i used in front of field. But this request is doing the same and is easier to handle.

Since documentation on laravel join is quite full of example. I hope this will be enough to help you.


问:
How to send an Excel chart from outlook macro
I got to the point where I run an outlook macro with rules and alerts.

The macro searches the inbox for a mail from mail address, when it finds it, it moves it to a sub folder, then extracts only the Number from the mail body, open an Excel, paste the number and mail date into the Excel on the next free row, updates the Excel, saves it and closes it.

last it moves the mail to the DONE directory and mark it as read.

In the Excel there is a pivot table that creates a graph (Chart 3).

Now I want to send that graph from the excel to mail recipients,
I found many ways to mail the graph from Excel but not from outlook macro.

here is what I have so far:

```<code>Sub MoveItems(Item As Outlook.MailItem)
'****************************************************************************
'* Find mail from sender and move them from the inbox to the rquests folder *
'****************************************************************************
Dim myNameSpace As Outlook.NameSpace
Dim myInbox As Outlook.Folder
Dim myDestFolder As Outlook.Folder
Dim myItems As Outlook.Items
Dim myItem As Object
Set myNameSpace = Application.GetNamespace("MAPI")
Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
Set myItems = myInbox.Items
Set myDestFolder = myInbox.Folders("Rquests")
Set myItem = myItems.Find("[SenderEmailAddress] = 'mail@domain.com'")
While TypeName(myItem) <> "Nothing"
    If myItem.UnRead = True Then
        myItem.Move myDestFolder
        Set myItem = myItems.FindNext
    End If
Wend
'*********************************************************
'* run the Process that extruct the number from the mail *
'*********************************************************
ProcessRequests
End Sub
---------------------------------------------------------------------------
Sub MoveItems2()
'*******************************************************************
'* Move the processed mail from the rquests to the  RQ_Done folder *
'*******************************************************************
Dim myNameSpace As Outlook.NameSpace
Dim mySourceFolder As Outlook.Folder
Dim myDestFolder As Outlook.Folder
Dim myItems As Outlook.Items
Dim myItem As Object
Set myNameSpace = Application.GetNamespace("MAPI")
Set mySourceFolder = myNameSpace.GetDefaultFolder(olFolderInbox).Folders("Rquests")
Set myItems = mySourceFolder.Items
Set myDestFolder = mySourceFolder.Folders("RQ_Done")
Set myItem = myItems.Find("[SenderEmailAddress] = 'mail@domain.com'")
While TypeName(myItem) <> "Nothing"
    myItem.UnRead = False
    myItem.Move myDestFolder
    Set myItem = myItems.FindNext
Wend
End Sub
---------------------------------------------------------------------------
Sub ProcessRequests()
On Error Resume Next
Set myOlApp = Outlook.Application
Set myNameSpace = myOlApp.GetNamespace("mapi")
Dim msgtext As String
Dim TimeStamp As Date
'set the outlook folder to look at
Set myfolder = myNameSpace.GetDefaultFolder(olFolderInbox).Folders("Rquests")
'set excel parameters
Dim xlApp As Object
Dim xlWkb As Object
Dim xlSheet As Object
Dim rCount As Long
Set xlApp = CreateObject("excel.application.12")
xlApp.Visible = True
'Open existing excel
Set xlWkb = xlApp.Workbooks.Open("C:\pathtofile\QTYperday.xlsm")
Set xlSheet = xlWkb.Sheets("Data")
xlApp.Worksheets("Data").Activate
'Find the next empty line of the worksheet
rCount = xlSheet.Range("A" & xlSheet.Rows.Count).End(-4162).Row
rCount = rCount + 1
'Search all mail items in current mail directory
For i = 1 To myfolder.Items.Count
    Set myItem = myfolder.Items(i)
    sender = myItem.SenderEmailAddress
    If sender = "mail@domain.com" Then
        msgtext = myItem.Body
        TimeStamp = myItem.SentOn
        'send the body of the mail message to the Function "onlyDigits" that will extract the numbers from it
        Dim myStr As String
        myStr = onlyDigits(msgtext)
        If myStr = "" Then
            myStr = "0"
        End If
        'get the date from date time
        mailDateY = DatePart("yyyy", TimeStamp) ' get Year
        MailDateM = DatePart("m", TimeStamp)    ' get Month
        MailDateD = DatePart("d", TimeStamp)    ' get Day
        MailDateW = DatePart("w", TimeStamp)    ' Get day of the week
        MailDate = (mailDateY & "/" & MailDateM & "/" & MailDateD)  ' Combine it to be a date again
        'set the day of the week
        If MailDateW = 1 Then
            MailDateW = "Sun"
        ElseIf MailDateW = 2 Then
            MailDateW = "Mon"
        ElseIf MailDateW = 3 Then
            MailDateW = "Tue"
        ElseIf MailDateW = 4 Then
            MailDateW = "Wed"
        ElseIf MailDateW = 5 Then
            MailDateW = "Thu"
        End If
        MailDay = MailDateW
        'write to excel
        xlSheet.Range("A" & rCount).value = myStr
        xlSheet.Range("B" & rCount).value = MailDate
        xlSheet.Range("C" & rCount).value = MailDateW
    Else
    End If
Next
xlApp.Worksheets("Sheet2").Activate
'Rerash and Save the excel
xlWkb.RefreshAll
xlWkb.Save
'************************
'mail the chart to list *
'************************
'Here I need the code to get the graph from excel and paste it to the email
'as an excel object or picture, It does not matter
'next is sending the mail with the graph (as attachement?)
Dim objMail As Outlook.MailItem
Set objMail = Application.CreateItem(olMailItem)
With objMail
        .To = "me@email.com"
        .CC = ""
        .BCC = ""
        .Subject = "Subject Line"
        .Body = "Body of mail"
        .Attachments.Add 'What, how?
        .Send
End With
xlWkb.Close 1
xlApp.Quit
' Mark processed mail as Read and move it to RQ_done folder
MoveItems2
End Sub
---------------------------------------------------------------------------
Function onlyDigits(s As String) As String
'************************************
'* extruct the number from the mail *
'************************************
Dim retval As String    ' This is the return string.      '
Dim i As Integer        ' Counter for character position. '
' Initialise return string to empty                       '
retval = ""
' For every character in input string, copy digits to     '
'   return string.                                        '
For i = 1 To Len(s)
    If Mid(s, i, 1) >= "0" And Mid(s, i, 1) <= "9" Then
        retval = retval + Mid(s, i, 1)
        If retval = "" Then
            retval = "0"
        End If
    End If
Next
' Then return the return string.                          '
onlyDigits = retval
End Function
</code>```

I have this piece of code that runs on the Excel, it saves the chart as gif file attach it and send it, is there a way to covert it to work from outlook?

```<code>Sub SaveSend_Embedded_Chart()
'Working in 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
    Dim OutApp As Object
    Dim OutMail As Object
    Dim Fname As String

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    'File path/name of the gif file
     Fname = Environ$("temp") & "\My_Sales1.gif"

    'Save Chart named "Chart 1" as gif file
    'If you hold down the CTRL key when you select the chart
    'in 2000-2013 you see the name in the Name box(formula bar)
     ActiveWorkbook.Worksheets("Sheet2").ChartObjects("Chart 3").Chart.Export _
            Filename:=Fname, FilterName:="GIF"

    On Error Resume Next
    With OutMail
        .To = "eeee@eeee.com"
        .CC = ""
        .BCC = ""
        .Subject = "This is the Subject line"
        .Body = "Hi there"
        .Attachments.Add Fname
        .Send   'or use .Display
     End With
     On Error GoTo 0

    'Delete the gif file
     Kill Fname

     Set OutMail = Nothing
     Set OutApp = Nothing
End Sub
</code>```

答:
Replace Outlook Objects with Excel Objects,  there is no need to create Outlook Application instance in the Outlook VBA macro:

Example

```<code>Option Explicit
Sub SaveSend_Embedded_Chart()
    Dim Fname As String

    Dim App As Excel.Application
    Dim xlBook As Excel.Workbook

    Dim FilePath As String

    Path = "C:\Temp\"
    FileName = "Temp.xlsx"

    On Error Resume Next
    Set App = GetObject(, "Excel.Application")
    If Err <> 0 Then
        Application.StatusBar = "Please wait while Excel source is opened ... "
        Set App = CreateObject("Excel.Application")
        xlStarted = True
    End If
    On Error GoTo 0

    '// Open the workbook to input the data
    Set xlBook = App.Workbooks.Open(Path & FileName)

    'File path/name of the gif file
     Fname = Environ$("temp") & "\My_Sales1.gif"

    'Save Chart named "Chart 1" as gif file
    'If you hold down the CTRL key when you select the chart
    'in 2000-2013 you see the name in the Name box(formula bar)
     xlBook.Worksheets("Sheet2").ChartObjects("Chart 3").Chart.Export _
            FileName:=Fname, FilterName:="GIF"

    With OutMail
        .To = "email@pcom"
        .CC = ""
        .BCC = ""
        .Subject = "This is the Subject line"
        .Body = "Hi there"
        .Attachments.Add Fname
        .Send   'or use .Display
     End With

    'Delete the gif file
     Kill Fname

    xlBook.Close SaveChanges:=True
    If xlStarted Then
        App.Quit
    End If

    Set App = Nothing
    Set xlBook = Nothing
End Sub
</code>```

Body:
I got to the point where I run an outlook macro with rules and alerts.

The macro searches the inbox for a mail from mail address, when it finds it, it moves it to a sub folder, then extracts only the Number from the mail body, open an Excel, paste the number and mail date into the Excel on the next free row, updates the Excel, saves it and closes it.

last it moves the mail to the DONE directory and mark it as read.

In the Excel there is a pivot table that creates a graph (Chart 3).

Now I want to send that graph from the excel to mail recipients,
I found many ways to mail the graph from Excel but not from outlook macro.

here is what I have so far:

Sub MoveItems(Item As Outlook.MailItem)
'****************************************************************************
'* Find mail from sender and move them from the inbox to the rquests folder *
'****************************************************************************
Dim myNameSpace As Outlook.NameSpace
Dim myInbox As Outlook.Folder
Dim myDestFolder As Outlook.Folder
Dim myItems As Outlook.Items
Dim myItem As Object
Set myNameSpace = Application.GetNamespace("MAPI")
Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
Set myItems = myInbox.Items
Set myDestFolder = myInbox.Folders("Rquests")
Set myItem = myItems.Find("[SenderEmailAddress] = 'mail@domain.com'")
While TypeName(myItem) <> "Nothing"
    If myItem.UnRead = True Then
        myItem.Move myDestFolder
        Set myItem = myItems.FindNext
    End If
Wend
'*********************************************************
'* run the Process that extruct the number from the mail *
'*********************************************************
ProcessRequests
End Sub
---------------------------------------------------------------------------
Sub MoveItems2()
'*******************************************************************
'* Move the processed mail from the rquests to the  RQ_Done folder *
'*******************************************************************
Dim myNameSpace As Outlook.NameSpace
Dim mySourceFolder As Outlook.Folder
Dim myDestFolder As Outlook.Folder
Dim myItems As Outlook.Items
Dim myItem As Object
Set myNameSpace = Application.GetNamespace("MAPI")
Set mySourceFolder = myNameSpace.GetDefaultFolder(olFolderInbox).Folders("Rquests")
Set myItems = mySourceFolder.Items
Set myDestFolder = mySourceFolder.Folders("RQ_Done")
Set myItem = myItems.Find("[SenderEmailAddress] = 'mail@domain.com'")
While TypeName(myItem) <> "Nothing"
    myItem.UnRead = False
    myItem.Move myDestFolder
    Set myItem = myItems.FindNext
Wend
End Sub
---------------------------------------------------------------------------
Sub ProcessRequests()
On Error Resume Next
Set myOlApp = Outlook.Application
Set myNameSpace = myOlApp.GetNamespace("mapi")
Dim msgtext As String
Dim TimeStamp As Date
'set the outlook folder to look at
Set myfolder = myNameSpace.GetDefaultFolder(olFolderInbox).Folders("Rquests")
'set excel parameters
Dim xlApp As Object
Dim xlWkb As Object
Dim xlSheet As Object
Dim rCount As Long
Set xlApp = CreateObject("excel.application.12")
xlApp.Visible = True
'Open existing excel
Set xlWkb = xlApp.Workbooks.Open("C:\pathtofile\QTYperday.xlsm")
Set xlSheet = xlWkb.Sheets("Data")
xlApp.Worksheets("Data").Activate
'Find the next empty line of the worksheet
rCount = xlSheet.Range("A" & xlSheet.Rows.Count).End(-4162).Row
rCount = rCount + 1
'Search all mail items in current mail directory
For i = 1 To myfolder.Items.Count
    Set myItem = myfolder.Items(i)
    sender = myItem.SenderEmailAddress
    If sender = "mail@domain.com" Then
        msgtext = myItem.Body
        TimeStamp = myItem.SentOn
        'send the body of the mail message to the Function "onlyDigits" that will extract the numbers from it
        Dim myStr As String
        myStr = onlyDigits(msgtext)
        If myStr = "" Then
            myStr = "0"
        End If
        'get the date from date time
        mailDateY = DatePart("yyyy", TimeStamp) ' get Year
        MailDateM = DatePart("m", TimeStamp)    ' get Month
        MailDateD = DatePart("d", TimeStamp)    ' get Day
        MailDateW = DatePart("w", TimeStamp)    ' Get day of the week
        MailDate = (mailDateY & "/" & MailDateM & "/" & MailDateD)  ' Combine it to be a date again
        'set the day of the week
        If MailDateW = 1 Then
            MailDateW = "Sun"
        ElseIf MailDateW = 2 Then
            MailDateW = "Mon"
        ElseIf MailDateW = 3 Then
            MailDateW = "Tue"
        ElseIf MailDateW = 4 Then
            MailDateW = "Wed"
        ElseIf MailDateW = 5 Then
            MailDateW = "Thu"
        End If
        MailDay = MailDateW
        'write to excel
        xlSheet.Range("A" & rCount).value = myStr
        xlSheet.Range("B" & rCount).value = MailDate
        xlSheet.Range("C" & rCount).value = MailDateW
    Else
    End If
Next
xlApp.Worksheets("Sheet2").Activate
'Rerash and Save the excel
xlWkb.RefreshAll
xlWkb.Save
'************************
'mail the chart to list *
'************************
'Here I need the code to get the graph from excel and paste it to the email
'as an excel object or picture, It does not matter
'next is sending the mail with the graph (as attachement?)
Dim objMail As Outlook.MailItem
Set objMail = Application.CreateItem(olMailItem)
With objMail
        .To = "me@email.com"
        .CC = ""
        .BCC = ""
        .Subject = "Subject Line"
        .Body = "Body of mail"
        .Attachments.Add 'What, how?
        .Send
End With
xlWkb.Close 1
xlApp.Quit
' Mark processed mail as Read and move it to RQ_done folder
MoveItems2
End Sub
---------------------------------------------------------------------------
Function onlyDigits(s As String) As String
'************************************
'* extruct the number from the mail *
'************************************
Dim retval As String    ' This is the return string.      '
Dim i As Integer        ' Counter for character position. '
' Initialise return string to empty                       '
retval = ""
' For every character in input string, copy digits to     '
'   return string.                                        '
For i = 1 To Len(s)
    If Mid(s, i, 1) >= "0" And Mid(s, i, 1) <= "9" Then
        retval = retval + Mid(s, i, 1)
        If retval = "" Then
            retval = "0"
        End If
    End If
Next
' Then return the return string.                          '
onlyDigits = retval
End Function

I have this piece of code that runs on the Excel, it saves the chart as gif file attach it and send it, is there a way to covert it to work from outlook?

Sub SaveSend_Embedded_Chart()
'Working in 2000-2016
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
    Dim OutApp As Object
    Dim OutMail As Object
    Dim Fname As String

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    'File path/name of the gif file
     Fname = Environ$("temp") & "\My_Sales1.gif"

    'Save Chart named "Chart 1" as gif file
    'If you hold down the CTRL key when you select the chart
    'in 2000-2013 you see the name in the Name box(formula bar)
     ActiveWorkbook.Worksheets("Sheet2").ChartObjects("Chart 3").Chart.Export _
            Filename:=Fname, FilterName:="GIF"

    On Error Resume Next
    With OutMail
        .To = "eeee@eeee.com"
        .CC = ""
        .BCC = ""
        .Subject = "This is the Subject line"
        .Body = "Hi there"
        .Attachments.Add Fname
        .Send   'or use .Display
     End With
     On Error GoTo 0

    'Delete the gif file
     Kill Fname

     Set OutMail = Nothing
     Set OutApp = Nothing
End Sub

Body:
Replace Outlook Objects with Excel Objects,  there is no need to create Outlook Application instance in the Outlook VBA macro:

Example

Option Explicit
Sub SaveSend_Embedded_Chart()
    Dim Fname As String

    Dim App As Excel.Application
    Dim xlBook As Excel.Workbook

    Dim FilePath As String

    Path = "C:\Temp\"
    FileName = "Temp.xlsx"

    On Error Resume Next
    Set App = GetObject(, "Excel.Application")
    If Err <> 0 Then
        Application.StatusBar = "Please wait while Excel source is opened ... "
        Set App = CreateObject("Excel.Application")
        xlStarted = True
    End If
    On Error GoTo 0

    '// Open the workbook to input the data
    Set xlBook = App.Workbooks.Open(Path & FileName)

    'File path/name of the gif file
     Fname = Environ$("temp") & "\My_Sales1.gif"

    'Save Chart named "Chart 1" as gif file
    'If you hold down the CTRL key when you select the chart
    'in 2000-2013 you see the name in the Name box(formula bar)
     xlBook.Worksheets("Sheet2").ChartObjects("Chart 3").Chart.Export _
            FileName:=Fname, FilterName:="GIF"

    With OutMail
        .To = "email@pcom"
        .CC = ""
        .BCC = ""
        .Subject = "This is the Subject line"
        .Body = "Hi there"
        .Attachments.Add Fname
        .Send   'or use .Display
     End With

    'Delete the gif file
     Kill Fname

    xlBook.Close SaveChanges:=True
    If xlStarted Then
        App.Quit
    End If

    Set App = Nothing
    Set xlBook = Nothing
End Sub


问:
Create matrix all possible combinations for n numbers
So this is the first question that i post.
I'm having some problems with the creation of a matrix in Matlab.
I would like to create a matrix that containts all possible unique combinations for the numbers [1,2,3] (thus without any duplicate combinations).

Meaning that it will create a matrix that looks like the following:

1 2

1 3

1 2 3

2 3

Thanks in advance!

答:
I can't comment yet, not enough reputation...
As already said before, you can't have a non-rectangular matrix.

You can have the solution in cell-array form for instance, this code would do it (probably not the most efficient though):

```<code>function [ all_subsets ] = find_subsets( tab )
%UNTITLED2 Summary of this function goes here
%   Detailed explanation goes here
    if (isempty(tab))
        all_subsets = {[]};
    else
        subsets_1 = find_subsets(tab(2:end));

        Y = num2cell(ones(1, length(subsets_1)) * tab(1));
        subsets_2 = arrayfun(@(L, X) add_elem(L, X), subsets_1, Y, 'UniformOutput', false);
        all_subsets = [subsets_1 subsets_2];
    end

end

function [L2] = add_elem(L, X)
    L2 = L{1};
    L2(end+1)=X{1};
end
</code>```

And then you call:

```<code>find_subsets(1:3)
</code>```

EDIT:

This is actually reversing the elements, you can correct that with a post processing, or with :

```<code>        subsets_1 = find_subsets(tab(1:end-1));

        Y = num2cell(ones(1, length(subsets_1)) * tab(end));
</code>```

Body:
I can't comment yet, not enough reputation...
As already said before, you can't have a non-rectangular matrix.

You can have the solution in cell-array form for instance, this code would do it (probably not the most efficient though):

function [ all_subsets ] = find_subsets( tab )
%UNTITLED2 Summary of this function goes here
%   Detailed explanation goes here
    if (isempty(tab))
        all_subsets = {[]};
    else
        subsets_1 = find_subsets(tab(2:end));

        Y = num2cell(ones(1, length(subsets_1)) * tab(1));
        subsets_2 = arrayfun(@(L, X) add_elem(L, X), subsets_1, Y, 'UniformOutput', false);
        all_subsets = [subsets_1 subsets_2];
    end

end

function [L2] = add_elem(L, X)
    L2 = L{1};
    L2(end+1)=X{1};
end

And then you call:

find_subsets(1:3)

EDIT:

This is actually reversing the elements, you can correct that with a post processing, or with :

        subsets_1 = find_subsets(tab(1:end-1));

        Y = num2cell(ones(1, length(subsets_1)) * tab(end));


问:
Angular 2 show popup and redirect
I need show popup showing some message and then redirect to another component.But the thing is it doesn't show popup but redirecting to another component.i have tried the following code which redirects to another component.Since i'm newbie to angular 2 kindly help me.

Note : popwindow is showing if i dnt redirect to another component

```<code>import { Component,OnInit, ViewEncapsulation,ViewContainerRef } from '@angular/core';
    import { NgForm } from '@angular/forms';
    import { HttpService } from 'app/http.service';
    import { Router } from '@angular/router';
    import { Overlay } from 'angular2-modal';
    import { Modal } from 'angular2-modal/plugins/bootstrap';

    @Component({
      selector: 'app-registration',
      templateUrl: './registration.component.html',
      styleUrls: ['./registration.component.css'],
      encapsulation: ViewEncapsulation.None
    })
    export class RegistrationComponent implements OnInit {

      constructor(private httpService : HttpService,private router: Router,overlay: Overlay, vcRef: ViewContainerRef, public modal: Modal) {
        overlay.defaultViewContainer = vcRef;
       }

      ngOnInit() {
      }

      onsubmit(form: NgForm){
        this.httpService.sendData(form.value).subscribe(data =>{
          if(data.data == 1 ){this.modal.alert().title('Message').body('Successfully registered').open();
           this.router.navigate(['/login']);}

      },error => {
        if(error)
        {
          this.modal.alert().title('Message').body('Server is not reachable').open();
        }
      });

      }

    }
</code>```

答:
```<code>onsubmit(form: NgForm){
        this.httpService.sendData(form.value).subscribe(data =>{
        if(data.data == 1 ){this.modal.alert().title('Message').body('Successfully registered').open();
        setTimeout(() => {
           this.router.navigate(['/login']);
        }, 2000);
}
</code>```

Title: Angular 2 show popup and redirect

Body:
I need show popup showing some message and then redirect to another component.But the thing is it doesn't show popup but redirecting to another component.i have tried the following code which redirects to another component.Since i'm newbie to angular 2 kindly help me.

Note : popwindow is showing if i dnt redirect to another component

import { Component,OnInit, ViewEncapsulation,ViewContainerRef } from '@angular/core';
    import { NgForm } from '@angular/forms';
    import { HttpService } from 'app/http.service';
    import { Router } from '@angular/router';
    import { Overlay } from 'angular2-modal';
    import { Modal } from 'angular2-modal/plugins/bootstrap';

    @Component({
      selector: 'app-registration',
      templateUrl: './registration.component.html',
      styleUrls: ['./registration.component.css'],
      encapsulation: ViewEncapsulation.None
    })
    export class RegistrationComponent implements OnInit {

      constructor(private httpService : HttpService,private router: Router,overlay: Overlay, vcRef: ViewContainerRef, public modal: Modal) {
        overlay.defaultViewContainer = vcRef;
       }

      ngOnInit() {
      }

      onsubmit(form: NgForm){
        this.httpService.sendData(form.value).subscribe(data =>{
          if(data.data == 1 ){this.modal.alert().title('Message').body('Successfully registered').open();
           this.router.navigate(['/login']);}

      },error => {
        if(error)
        {
          this.modal.alert().title('Message').body('Server is not reachable').open();
        }
      });

      }

    }


问:
Fonts not working when deploying jasperreport in PDF from web app
I'm having some issues with the fonts when I'm deploying the reports in my web app. The fonts I want to have in my result pdfs are Arial, Calibri and Century Gothic.

I followed all the steps pointed here but couldn't get it working.

Here's what I did:

I modified the content of my jasperreports_extension.properties like following:

```<code>net.sf.jasperreports.extension.registry.factory.simple.font.families=net.sf.jasperreports.engine.fonts.SimpleFontExtensionsRegistryFactory
net.sf.jasperreports.extension.simple.font.families.dejavu=net/sf/jasperreports/fonts/fonts.xml
net.sf.jasperreports.extension.simple.font.families.arial=net/sf/jasperreports/fonts/fonts.xml
net.sf.jasperreports.extension.simple.font.families.calibri=net/sf/jasperreports/fonts/fonts.xml
net.sf.jasperreports.extension.simple.font.families.centurygothic=net/sf/jasperreports/fonts/fonts.xml
</code>```

Then at net\sf\jasperreports\fonts I put the three folders for the fonts containing the four styles (normal, bold, italic and bold-italic) for each of the fonts before mentioned.

Also, modified the fonts.xml at net/sf/jasperreports/fonts and it looks like this now:

```<code><?xml version="1.0" encoding="UTF-8"?>

<fontFamilies>

    <fontFamily name="DejaVu Sans">
        <normal>net/sf/jasperreports/fonts/dejavu/DejaVuSans.ttf</normal>
        <bold>net/sf/jasperreports/fonts/dejavu/DejaVuSans-Bold.ttf</bold>
        <italic>net/sf/jasperreports/fonts/dejavu/DejaVuSans-Oblique.ttf</italic>
        <boldItalic>net/sf/jasperreports/fonts/dejavu/DejaVuSans-BoldOblique.ttf</boldItalic>
        <pdfEncoding>Identity-H</pdfEncoding>
        <pdfEmbedded>true</pdfEmbedded>
        <exportFonts>
            <export key="net.sf.jasperreports.html">'DejaVu Sans', Arial, Helvetica, sans-serif</export>
            <export key="net.sf.jasperreports.xhtml">'DejaVu Sans', Arial, Helvetica, sans-serif</export>
        </exportFonts>
        <!--
        <locales>
            <locale>en_US</locale>
            <locale>de_DE</locale>
        </locales>
        -->
    </fontFamily>

    <fontFamily name="DejaVu Serif">
        <normal>net/sf/jasperreports/fonts/dejavu/DejaVuSerif.ttf</normal>
        <bold>net/sf/jasperreports/fonts/dejavu/DejaVuSerif-Bold.ttf</bold>
        <italic>net/sf/jasperreports/fonts/dejavu/DejaVuSerif-Italic.ttf</italic>
        <boldItalic>net/sf/jasperreports/fonts/dejavu/DejaVuSerif-BoldItalic.ttf</boldItalic>
        <pdfEncoding>Identity-H</pdfEncoding>
        <pdfEmbedded>true</pdfEmbedded>
        <exportFonts>
            <export key="net.sf.jasperreports.html">'DejaVu Serif', 'Times New Roman', Times, serif</export>
            <export key="net.sf.jasperreports.xhtml">'DejaVu Serif', 'Times New Roman', Times, serif</export>
        </exportFonts>
    </fontFamily>

    <fontFamily name="DejaVu Sans Mono">
        <normal>net/sf/jasperreports/fonts/dejavu/DejaVuSansMono.ttf</normal>
        <bold>net/sf/jasperreports/fonts/dejavu/DejaVuSansMono-Bold.ttf</bold>
        <italic>net/sf/jasperreports/fonts/dejavu/DejaVuSansMono-Oblique.ttf</italic>
        <boldItalic>net/sf/jasperreports/fonts/dejavu/DejaVuSansMono-BoldOblique.ttf</boldItalic>
        <pdfEncoding>Identity-H</pdfEncoding>
        <pdfEmbedded>true</pdfEmbedded>
        <exportFonts>
            <export key="net.sf.jasperreports.html">'DejaVu Sans Mono', 'Courier New', Courier, monospace</export>
            <export key="net.sf.jasperreports.xhtml">'DejaVu Sans Mono', 'Courier New', Courier, monospace</export>
        </exportFonts>
    </fontFamily>

    <!--
        Mapping Java logical fonts, for the sake of HTML export only.
    -->

    <fontFamily name="SansSerif">
        <exportFonts>
            <export key="net.sf.jasperreports.html">'DejaVu Sans', Arial, Helvetica, sans-serif</export>
            <export key="net.sf.jasperreports.xhtml">'DejaVu Sans', Arial, Helvetica, sans-serif</export>
        </exportFonts>
    </fontFamily>
    <fontFamily name="Serif">
        <exportFonts>
            <export key="net.sf.jasperreports.html">'DejaVu Serif', 'Times New Roman', Times, serif</export>
            <export key="net.sf.jasperreports.xhtml">'DejaVu Serif', 'Times New Roman', Times, serif</export>
        </exportFonts>
    </fontFamily>
    <fontFamily name="Monospaced">
        <exportFonts>
            <export key="net.sf.jasperreports.html">'DejaVu Sans Mono', 'Courier New', Courier, monospace</export>
            <export key="net.sf.jasperreports.xhtml">'DejaVu Sans Mono', 'Courier New', Courier, monospace</export>
        </exportFonts>
    </fontFamily>

    <fontFamily name="Arial">
       <normal>net/sf/jasperreports/fonts/arial/arial.ttf</normal>
       <bold>net/sf/jasperreports/fonts/arial/ArialBold.ttf</bold>
       <italic>net/sf/jasperreports/fonts/arial/ArialItalic.ttf</italic>
       <boldItalic>net/sf/jasperreports/fonts/arial/ArialBoldItalic.ttf</boldItalic>
       <pdfEncoding>Identity-H</pdfEncoding>
       <pdfEmbedded>true</pdfEmbedded>
       <exportFonts>
           <export key="net.sf.jasperreports.html">'Arial'</export>
           <export key="net.sf.jasperreports.xhtml">'Arial'</export>
       </exportFonts>
    </fontFamily>

    <fontFamily name="Calibri">
       <normal>net/sf/jasperreports/fonts/calibri/calibri.ttf</normal>
       <bold>net/sf/jasperreports/fonts/calibri/calibri-bold.ttf</bold>
       <italic>net/sf/jasperreports/fonts/calibri/calibri-italic.ttf</italic>
       <boldItalic>net/sf/jasperreports/fonts/calibri/calibri-bold-italic.ttf</boldItalic>
       <pdfEncoding>Identity-H</pdfEncoding>
       <pdfEmbedded>true</pdfEmbedded>
       <exportFonts>
           <export key="net.sf.jasperreports.html">'Calibri'</export>
           <export key="net.sf.jasperreports.xhtml">'Calibri'</export>
       </exportFonts>
    </fontFamily>

    <fontFamily name="Century Gothic">
       <normal>net/sf/jasperreports/fonts/centurygothic/century-gothic.ttf</normal>
       <bold>net/sf/jasperreports/fonts/centurygothic/century-gothic-bold.ttf</bold>
       <italic>net/sf/jasperreports/fonts/centurygothic/century-gothic-italic.ttf</italic>
       <boldItalic>net/sf/jasperreports/fonts/centurygothic/century-gothic-bold-italic.ttf</boldItalic>
       <pdfEncoding>Identity-H</pdfEncoding>
       <pdfEmbedded>true</pdfEmbedded>
       <exportFonts>
           <export key="net.sf.jasperreports.html">'Century Gothic'</export>
           <export key="net.sf.jasperreports.xhtml">'Century Gothic'</export>
       </exportFonts>
    </fontFamily>

</fontFamilies>
</code>```

Note that I just added the last three fonts.

After that I prepared the jar file and put it in my app classpath as mandatory. So far I just got the report exported with normal Sanserif font...

I don't know what I'm doing wrong, any ideas?

Thanks!

Quick informative note: I'm using Jaspersoft Studio Community edition (6.3.0) and my app is deployed in a JBoss server.

答:
I finally found out what was happening in my case and now it's working.

When I introduced the fonts (.ttf extension) in Jaspersoft Studio Windows->Preferences->Fonts I selected a wrong value for the PDF Encoding selection combo. I first selected CP1252 (Western European ANSI aka WinAnsi) which is WRONG if you want to export reports in PDF, then I chose Identity-H (Unicode with horizontal writing) instead and it worked fine.

However, what I still don't understand is: if in my report I'm only using Calibri and Century Gothic fonts, why in earth when I go to see the fonts used in my PDF (File->Properties->Fonts) I get also Helvetica in the list of fonts used?

Body:
I'm having some issues with the fonts when I'm deploying the reports in my web app. The fonts I want to have in my result pdfs are Arial, Calibri and Century Gothic.

I followed all the steps pointed here but couldn't get it working.

Here's what I did:

I modified the content of my jasperreports_extension.properties like following:

net.sf.jasperreports.extension.registry.factory.simple.font.families=net.sf.jasperreports.engine.fonts.SimpleFontExtensionsRegistryFactory
net.sf.jasperreports.extension.simple.font.families.dejavu=net/sf/jasperreports/fonts/fonts.xml
net.sf.jasperreports.extension.simple.font.families.arial=net/sf/jasperreports/fonts/fonts.xml
net.sf.jasperreports.extension.simple.font.families.calibri=net/sf/jasperreports/fonts/fonts.xml
net.sf.jasperreports.extension.simple.font.families.centurygothic=net/sf/jasperreports/fonts/fonts.xml

Then at net\sf\jasperreports\fonts I put the three folders for the fonts containing the four styles (normal, bold, italic and bold-italic) for each of the fonts before mentioned.

Also, modified the fonts.xml at net/sf/jasperreports/fonts and it looks like this now:

<?xml version="1.0" encoding="UTF-8"?>

<fontFamilies>

    <fontFamily name="DejaVu Sans">
        <normal>net/sf/jasperreports/fonts/dejavu/DejaVuSans.ttf</normal>
        <bold>net/sf/jasperreports/fonts/dejavu/DejaVuSans-Bold.ttf</bold>
        <italic>net/sf/jasperreports/fonts/dejavu/DejaVuSans-Oblique.ttf</italic>
        <boldItalic>net/sf/jasperreports/fonts/dejavu/DejaVuSans-BoldOblique.ttf</boldItalic>
        <pdfEncoding>Identity-H</pdfEncoding>
        <pdfEmbedded>true</pdfEmbedded>
        <exportFonts>
            <export key="net.sf.jasperreports.html">'DejaVu Sans', Arial, Helvetica, sans-serif</export>
            <export key="net.sf.jasperreports.xhtml">'DejaVu Sans', Arial, Helvetica, sans-serif</export>
        </exportFonts>

    </fontFamily>

    <fontFamily name="DejaVu Serif">
        <normal>net/sf/jasperreports/fonts/dejavu/DejaVuSerif.ttf</normal>
        <bold>net/sf/jasperreports/fonts/dejavu/DejaVuSerif-Bold.ttf</bold>
        <italic>net/sf/jasperreports/fonts/dejavu/DejaVuSerif-Italic.ttf</italic>
        <boldItalic>net/sf/jasperreports/fonts/dejavu/DejaVuSerif-BoldItalic.ttf</boldItalic>
        <pdfEncoding>Identity-H</pdfEncoding>
        <pdfEmbedded>true</pdfEmbedded>
        <exportFonts>
            <export key="net.sf.jasperreports.html">'DejaVu Serif', 'Times New Roman', Times, serif</export>
            <export key="net.sf.jasperreports.xhtml">'DejaVu Serif', 'Times New Roman', Times, serif</export>
        </exportFonts>
    </fontFamily>

    <fontFamily name="DejaVu Sans Mono">
        <normal>net/sf/jasperreports/fonts/dejavu/DejaVuSansMono.ttf</normal>
        <bold>net/sf/jasperreports/fonts/dejavu/DejaVuSansMono-Bold.ttf</bold>
        <italic>net/sf/jasperreports/fonts/dejavu/DejaVuSansMono-Oblique.ttf</italic>
        <boldItalic>net/sf/jasperreports/fonts/dejavu/DejaVuSansMono-BoldOblique.ttf</boldItalic>
        <pdfEncoding>Identity-H</pdfEncoding>
        <pdfEmbedded>true</pdfEmbedded>
        <exportFonts>
            <export key="net.sf.jasperreports.html">'DejaVu Sans Mono', 'Courier New', Courier, monospace</export>
            <export key="net.sf.jasperreports.xhtml">'DejaVu Sans Mono', 'Courier New', Courier, monospace</export>
        </exportFonts>
    </fontFamily>

    <fontFamily name="SansSerif">
        <exportFonts>
            <export key="net.sf.jasperreports.html">'DejaVu Sans', Arial, Helvetica, sans-serif</export>
            <export key="net.sf.jasperreports.xhtml">'DejaVu Sans', Arial, Helvetica, sans-serif</export>
        </exportFonts>
    </fontFamily>
    <fontFamily name="Serif">
        <exportFonts>
            <export key="net.sf.jasperreports.html">'DejaVu Serif', 'Times New Roman', Times, serif</export>
            <export key="net.sf.jasperreports.xhtml">'DejaVu Serif', 'Times New Roman', Times, serif</export>
        </exportFonts>
    </fontFamily>
    <fontFamily name="Monospaced">
        <exportFonts>
            <export key="net.sf.jasperreports.html">'DejaVu Sans Mono', 'Courier New', Courier, monospace</export>
            <export key="net.sf.jasperreports.xhtml">'DejaVu Sans Mono', 'Courier New', Courier, monospace</export>
        </exportFonts>
    </fontFamily>

    <fontFamily name="Arial">
       <normal>net/sf/jasperreports/fonts/arial/arial.ttf</normal>
       <bold>net/sf/jasperreports/fonts/arial/ArialBold.ttf</bold>
       <italic>net/sf/jasperreports/fonts/arial/ArialItalic.ttf</italic>
       <boldItalic>net/sf/jasperreports/fonts/arial/ArialBoldItalic.ttf</boldItalic>
       <pdfEncoding>Identity-H</pdfEncoding>
       <pdfEmbedded>true</pdfEmbedded>
       <exportFonts>
           <export key="net.sf.jasperreports.html">'Arial'</export>
           <export key="net.sf.jasperreports.xhtml">'Arial'</export>
       </exportFonts>
    </fontFamily>

    <fontFamily name="Calibri">
       <normal>net/sf/jasperreports/fonts/calibri/calibri.ttf</normal>
       <bold>net/sf/jasperreports/fonts/calibri/calibri-bold.ttf</bold>
       <italic>net/sf/jasperreports/fonts/calibri/calibri-italic.ttf</italic>
       <boldItalic>net/sf/jasperreports/fonts/calibri/calibri-bold-italic.ttf</boldItalic>
       <pdfEncoding>Identity-H</pdfEncoding>
       <pdfEmbedded>true</pdfEmbedded>
       <exportFonts>
           <export key="net.sf.jasperreports.html">'Calibri'</export>
           <export key="net.sf.jasperreports.xhtml">'Calibri'</export>
       </exportFonts>
    </fontFamily>

    <fontFamily name="Century Gothic">
       <normal>net/sf/jasperreports/fonts/centurygothic/century-gothic.ttf</normal>
       <bold>net/sf/jasperreports/fonts/centurygothic/century-gothic-bold.ttf</bold>
       <italic>net/sf/jasperreports/fonts/centurygothic/century-gothic-italic.ttf</italic>
       <boldItalic>net/sf/jasperreports/fonts/centurygothic/century-gothic-bold-italic.ttf</boldItalic>
       <pdfEncoding>Identity-H</pdfEncoding>
       <pdfEmbedded>true</pdfEmbedded>
       <exportFonts>
           <export key="net.sf.jasperreports.html">'Century Gothic'</export>
           <export key="net.sf.jasperreports.xhtml">'Century Gothic'</export>
       </exportFonts>
    </fontFamily>

</fontFamilies>

Note that I just added the last three fonts.

After that I prepared the jar file and put it in my app classpath as mandatory. So far I just got the report exported with normal Sanserif font...

I don't know what I'm doing wrong, any ideas?

Thanks!

Quick informative note: I'm using Jaspersoft Studio Community edition (6.3.0) and my app is deployed in a JBoss server.


问:
How do I run shell with custom Error handler?
I have custom AppError class which starts with

App::import('Core', 'Error');

When I try to run any shell script I run into "Fatal error: cannot redeclare class ErrorHandler in ...\cake\libs\error". It seems the ErrorHandler for console is loaded...

答:
Why don't you simply extend the ErrorHandler class if it is already loaded?</p>

```<code><?php
class AppError extends ErrorHandler {
}
?>
</code>```

Body:
Why don't you simply extend the ErrorHandler class if it is already loaded?

<?php
class AppError extends ErrorHandler {
}
?>


问:
Change react-bootstrap OverlayTrigger Popover's content while displayed
I am using react-boostrap's Popover with the OverlayTrigger class. My issue is that when I change the content on the Popover while it is displayed, it is properly resized but the position gets wrong. The popover maintains its top left corner position even if it is not aligned anymore with the OverlayTrigger

Here is what I am talking about:

Here is the code I am using in my render function, it's pretty straightforward:

```<code>const popover = (
        <Popover id={this.props.htKey} >
            {this.state.content}
        </Popover>
);

return (
            <OverlayTrigger
                trigger={["hover", "focus"]}
                delayShow={200}
                placement="top"
                overlay={popover}
                onEntered={this.startExtendTimer}
                onExited={this.resetContent}
            >
                <span>test</span>
            </OverlayTrigger>

 );
</code>```

The startExtenTimer calls a timeout that changes this.state.content after a few seconds (therefore resulting in the issue that I show on the picture)

How can I change the content of the popover while keeping the correct alignment?

答:
I found a solution here:

Similar question: https://github.com/react-bootstrap/react-bootstrap/issues/1438

Answer: https://github.com/react-bootstrap/react-overlays/pull/42

You can basically add a shouldUpdatePosition props to a Overlay component.

```<code><Overlay ... shouldUpdatePosition={true}  >
</code>```

My current issue with it is that I have an ugly delay before the repositioning. I am looking into it and will update if I found a solution

UPDATE: To remove this delay, I just had to immediately re-render the component holding the Overlay when the said overlay content get updated.

Body:
I am using react-boostrap's Popover with the OverlayTrigger class. My issue is that when I change the content on the Popover while it is displayed, it is properly resized but the position gets wrong. The popover maintains its top left corner position even if it is not aligned anymore with the OverlayTrigger

Here is what I am talking about:

Here is the code I am using in my render function, it's pretty straightforward:

const popover = (
        <Popover id={this.props.htKey} >
            {this.state.content}
        </Popover>
);

return (
            <OverlayTrigger
                trigger={["hover", "focus"]}
                delayShow={200}
                placement="top"
                overlay={popover}
                onEntered={this.startExtendTimer}
                onExited={this.resetContent}
            >
                test
            </OverlayTrigger>

 );

The startExtenTimer calls a timeout that changes this.state.content after a few seconds (therefore resulting in the issue that I show on the picture)

How can I change the content of the popover while keeping the correct alignment?

Body:
I found a solution here:

Similar question: https://github.com/react-bootstrap/react-bootstrap/issues/1438

Answer: https://github.com/react-bootstrap/react-overlays/pull/42

You can basically add a shouldUpdatePosition props to a Overlay component.

<Overlay ... shouldUpdatePosition={true}  >

My current issue with it is that I have an ugly delay before the repositioning. I am looking into it and will update if I found a solution

UPDATE: To remove this delay, I just had to immediately re-render the component holding the Overlay when the said overlay content get updated.


问:
how to post on google plus pages through api?
how to post on Google+ pages through API using php

while searching for Google+ API got Google page API
( https://developers.google.com/+/api/pages-signup ) which allows user to post on Google+ pages
but to white list this API need to apply for Google+ page API

i am not getting any documentation for Google+ page API (how to post on pages)

答:
We have tried to found another ways to post on Google+ but don't got any solution because Google+ is providing higher securty for writing permission.

Google+ default providing permission which is read permission and using our regular google account we can easily do it but we want to post on Google+ so we'll need google permission and for permission we'll need to create google domain account.

Please check this note which is google said:

Important: The access.domainRestricted property must be set to true for posts using the Google+ Domains API. Posts in Google+ are private by default so you must also specify the access.items property to choose the audience within the domain that is authorized to view the post.

And grant permissions which is google also said:

Required - Grants permission for the app to create posts or comments on behalf of a user. The Google+ Domains API only allows creation of restricted posts, and only allows comments to be added to restricted posts.

You can check these bellows links :

https://developers.google.com/+/domains/posts/creating

https://support.google.com/plus/answer/2705802 https://developers.google.com/+/domains/api/activities/insert#auth

https://developers.google.com/+/domains/authentication/scopes

https://developers.google.com/+/domains/api/activities/insert


问:
Switch compiler on Matlab 2017a in Ubuntu OS
I am running a script that needs a cpp compiler. I'm using MATLAB on both Windows and Ubuntu. On windows, with:

```<code>MEX configured to use 'MinGW64 Compiler (C++)' for C++ language compilation.
</code>```

i have no problem.

On Ubuntu, i have:

```<code>MEX configured to use 'g++' for C++ language compilation.
</code>```

and when i try to compile me .cpp files i get this error:

```<code>Error using mex
/home/christosandsoren/17gr10409/deformable_models/texture_functions/build_km_tree.cpp: In function ‘void mexFunction(int, mxArray**, int, const mxArray**)’:
/home/christosandsoren/17gr10409/deformable_models/texture_functions/build_km_tree.cpp:380:9: error: cannot convert ‘const size_t* {aka const long unsigned int*}’ to ‘const
int*’ in assignment
     dim = mxGetDimensions(prhs[0]);
         ^
/home/christosandsoren/17gr10409/deformable_models/texture_functions/build_km_tree.cpp:402:68: error: cannot convert ‘int*’ to ‘const size_t* {aka const long unsigned
int*}’ for argument ‘2’ to ‘mxArray* mxCreateNumericArray(size_t, const size_t*, mxClassID, mxComplexity)’
     plhs[0] = mxCreateNumericArray(2, dtree, mxDOUBLE_CLASS, mxREAL);
                                                                    ^

Error in compile_mex_functions (line 3)
mex build_km_tree.cpp % based on Euclidean distance
</code>```

I installed mingw-w64, by sudo apt-get install mingw-w64 but i still get the same result.

答:
The problem is that you use int and not mwSize for you dimension arrays:

```<code>const int *dim; // image dimensinos
int dtree[2];   // tree dimensions
</code>```

These should be:

```<code>const mwSize *dim; // image dimensinos
mwSize dtree[2];   // tree dimensions
</code>```

The description from MathWorks is:

mwSize is a type that represents size values, such as array dimensions. Use this function for cross-platform flexibility. By default, mwSize is equivalent to int in C.

When using the mex -largeArrayDims switch, mwSize is equivalent to size_t in C.

So the issue is that on one platform it is legal to use int* and on others it could be size_t*. However, it always correct to use mwSize*, since this is the portable solution.

As a side note I would write the first line like this:

```<code>mwSize const* dim; // image dimensinos
</code>```

This way is IMHO simpler to read, link to examples

Body:
I am running a script that needs a cpp compiler. I'm using MATLAB on both Windows and Ubuntu. On windows, with:

MEX configured to use 'MinGW64 Compiler (C++)' for C++ language compilation.

i have no problem.

On Ubuntu, i have:

MEX configured to use 'g++' for C++ language compilation.

and when i try to compile me .cpp files i get this error:

Error using mex
/home/christosandsoren/17gr10409/deformable_models/texture_functions/build_km_tree.cpp: In function ‘void mexFunction(int, mxArray**, int, const mxArray**)’:
/home/christosandsoren/17gr10409/deformable_models/texture_functions/build_km_tree.cpp:380:9: error: cannot convert ‘const size_t* {aka const long unsigned int*}’ to ‘const
int*’ in assignment
     dim = mxGetDimensions(prhs[0]);
         ^
/home/christosandsoren/17gr10409/deformable_models/texture_functions/build_km_tree.cpp:402:68: error: cannot convert ‘int*’ to ‘const size_t* {aka const long unsigned
int*}’ for argument ‘2’ to ‘mxArray* mxCreateNumericArray(size_t, const size_t*, mxClassID, mxComplexity)’
     plhs[0] = mxCreateNumericArray(2, dtree, mxDOUBLE_CLASS, mxREAL);
                                                                    ^

Error in compile_mex_functions (line 3)
mex build_km_tree.cpp % based on Euclidean distance

I installed mingw-w64, by sudo apt-get install mingw-w64 but i still get the same result.

Body:
The problem is that you use int and not mwSize for you dimension arrays:

const int *dim; // image dimensinos
int dtree[2];   // tree dimensions

These should be:

const mwSize *dim; // image dimensinos
mwSize dtree[2];   // tree dimensions

The description from MathWorks is:

mwSize is a type that represents size values, such as array dimensions. Use this function for cross-platform flexibility. By default, mwSize is equivalent to int in C.

When using the mex -largeArrayDims switch, mwSize is equivalent to size_t in C.

So the issue is that on one platform it is legal to use int* and on others it could be size_t*. However, it always correct to use mwSize*, since this is the portable solution.

As a side note I would write the first line like this:

mwSize const* dim; // image dimensinos

This way is IMHO simpler to read, link to examples


问:
EditText with DatePicker dialog not showing error text when date is not selected
i am working in a app that triggers local notification. for that i have coded to display a date in Edittext, such that when a user clicks on edit text, a date picker dialog opens.

In a case, if edittext is null, i have to show a error to the user and i have coded the below for that.

```<code>  btn_save.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
       if (et_reminderDate.getText().toString().trim().length() == 0) {
                        et_reminderDate.requestFocus();
                        et_reminderDate.setError(getResources().getString(R.string.reminder_selectDate));
                    } else if (et_reminderTime.getText().toString().trim().length() == 0) {
                        et_reminderTime.requestFocus();
                        et_reminderTime.setError(getResources().getString(R.string.reminder_time));
                    } else if (et_dateDue.getText().toString().toString().length() != 0) {
                        et_dateDue.setError(null);
                        et_dateDue.clearFocus();
                    } else if (et_reminderDate.getText().toString().toString().length() != 0) {
                        et_reminderDate.setError(null);
                        et_reminderDate.clearFocus();
                    }else{
My project coding goes here!
}
                            }
</code>```

But i am just getting the error icon. The error text is not shown.
As of my assumption, i have validated for text in edittext. Is that i have to validate for date in Edittext to find whether the date is null?

Note: In the same code, i am getting error message for edittext with text values. For example, edittext where user can enter name. Only for
Edittext with date picker i am not getting the error message!

Any help thanks!

答:
Try this code</p>

```<code>if (et_reminderTime.getText().toString().trim().isEmpty()) {
     et_reminderTime.setError(getResources().getString(R.string.reminder_time));
     et_reminderTime.requestFocus();
} else if(et_dateDue.getText().toString().toString().length()!=0) {
     //remove the request focus for et_dateDue
     et_dateDue.setError(null);
}
</code>```

Body:
i am working in a app that triggers local notification. for that i have coded to display a date in Edittext, such that when a user clicks on edit text, a date picker dialog opens.

In a case, if edittext is null, i have to show a error to the user and i have coded the below for that.

  btn_save.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
       if (et_reminderDate.getText().toString().trim().length() == 0) {
                        et_reminderDate.requestFocus();
                        et_reminderDate.setError(getResources().getString(R.string.reminder_selectDate));
                    } else if (et_reminderTime.getText().toString().trim().length() == 0) {
                        et_reminderTime.requestFocus();
                        et_reminderTime.setError(getResources().getString(R.string.reminder_time));
                    } else if (et_dateDue.getText().toString().toString().length() != 0) {
                        et_dateDue.setError(null);
                        et_dateDue.clearFocus();
                    } else if (et_reminderDate.getText().toString().toString().length() != 0) {
                        et_reminderDate.setError(null);
                        et_reminderDate.clearFocus();
                    }else{
My project coding goes here!
}
                            }

But i am just getting the error icon. The error text is not shown.
As of my assumption, i have validated for text in edittext. Is that i have to validate for date in Edittext to find whether the date is null?

Note: In the same code, i am getting error message for edittext with text values. For example, edittext where user can enter name. Only for
Edittext with date picker i am not getting the error message!

Any help thanks!

Body:
Try this code

if (et_reminderTime.getText().toString().trim().isEmpty()) {
     et_reminderTime.setError(getResources().getString(R.string.reminder_time));
     et_reminderTime.requestFocus();
} else if(et_dateDue.getText().toString().toString().length()!=0) {
     //remove the request focus for et_dateDue
     et_dateDue.setError(null);
}


问:
Gitkraken stuck at opening repo
Every time I open gitkrarken it gets stuck at opening repo icon. I can't open/clone/init repo.
I heard some others have the same problem but no one seems to know why this is happening and what the solution is.
Can anyone help with this?

UPDATE 1
Reinstalled it. Still having the same problem

答: Not a proper solution, but I'm having the same problem. I've been able to work around it by closing down Visual Studio before opening GitKraken.  It only gets stuck when opening and VS is already open.</p>

Title: Gitkraken stuck at opening repo


问:
How do I update Azure VM Agent, aka "waagent" package for CentOS 7?
I followed the guide here to update waagent using this command:

```<code>sudo yum install waagent
</code>```

However my server is unable to find the package. The reason why I want to update the package is because I'm unable to setup backup. Whenever I try, I'll get an error "VM agent is unable to communicate with the Azure Backup Service". Below is the screenshot.

Azure Operation Error

Edit: My virtual machine is not set up in the classic environment.

答: I decided to update waagent manually using the guide from the link I provided. After that I'm able to setup and run backups without problem.</p>

Body:
I followed the guide here to update waagent using this command:

sudo yum install waagent

However my server is unable to find the package. The reason why I want to update the package is because I'm unable to setup backup. Whenever I try, I'll get an error "VM agent is unable to communicate with the Azure Backup Service". Below is the screenshot.

Azure Operation Error

Edit: My virtual machine is not set up in the classic environment.