问:
Java WebService call ends with "Received a redirect, but followRedirects=false"
I have a webservice client generated from SoapUI and Apache CXF component. When I run it at Mule ESB server I receive the following error:

```<code>org.mule.transport.http.HttpClientMessageDispatcher - Received a redirect, but followRedirects=false. Response code: 401 Unauthorized
</code>```

Mule Flow looks like this:

The interesting fact here is that when I run it locally from Anypoint Studio everything works fine. How can I allow my service client to handle redirections. Is there any other error?

Here is my code:

```<code>URL wsdlURL = MPServiceService.WSDL_LOCATION;
MPServiceService ss = new MPServiceService(wsdlURL, SERVICE_NAME);
MPService port = ss.getDomino();

BindingProvider prov = (BindingProvider) port;
prov.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
        requestpath);
prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username);
prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);

String result = port.webServiceFoo();
return result;
</code>```

答:
The probem was caused by another application which had the following cxf config:

```<code><cxf:configuration name="CXF_Configuration" initializeStaticBusInstance="true" enableMuleSoapHeaders="false"  doc:name="CXF Configuration"/>
</code>```

We have changed initializeStaticBusInstance="false" so it looks like this:

```<code><cxf:configuration name="CXF_Configuration" initializeStaticBusInstance="false" enableMuleSoapHeaders="false"  doc:name="CXF Configuration"/>
</code>```

More info https://support.mulesoft.com/s/article/There-are-at-least-2-connectors-matching-protocol-https-when-using-CXF-generated-client

Body:
I have a webservice client generated from SoapUI and Apache CXF component. When I run it at Mule ESB server I receive the following error:

org.mule.transport.http.HttpClientMessageDispatcher - Received a redirect, but followRedirects=false. Response code: 401 Unauthorized

Mule Flow looks like this:

The interesting fact here is that when I run it locally from Anypoint Studio everything works fine. How can I allow my service client to handle redirections. Is there any other error?

Here is my code:

URL wsdlURL = MPServiceService.WSDL_LOCATION;
MPServiceService ss = new MPServiceService(wsdlURL, SERVICE_NAME);
MPService port = ss.getDomino();

BindingProvider prov = (BindingProvider) port;
prov.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
        requestpath);
prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username);
prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);

String result = port.webServiceFoo();
return result;

Body:
The probem was caused by another application which had the following cxf config:

<cxf:configuration name="CXF_Configuration" initializeStaticBusInstance="true" enableMuleSoapHeaders="false"  doc:name="CXF Configuration"/>

We have changed initializeStaticBusInstance="false" so it looks like this:

<cxf:configuration name="CXF_Configuration" initializeStaticBusInstance="false" enableMuleSoapHeaders="false"  doc:name="CXF Configuration"/>

More info https://support.mulesoft.com/s/article/There-are-at-least-2-connectors-matching-protocol-https-when-using-CXF-generated-client


来源: stackexchange

问:
How to sum the value of child items from a hierarchical list in a loop
How to sum the value of child items from a hierarchical list in a loop.

I need that during the loop in the list the values of the amount and price property contain the sum of these properties of the children.

Below are the two classes to be used to help me solve my problem.

```<code>namespace SGP.Dto.Custo
{
    public class PlanilhaCusto
    {
        public int id{ get; set; }
        public int parenteId{ get; set; }
        public string name { get; set; }
        public decimal amount{ get; set; }
        public decimal price{ get; set; }

        public PlanilhaCusto(int pId, int pParenteId, pName, decimal pAmount, decimal pPrice)
        {
            id = pId;
            parentId = pParentId;
            name = pName;
            amount = pAmount;
            price = pPrice;
        }
    }
}

namespace SGP.Dto.Custo
{
    public class ShowList
    {
        List<Dto.Custo.PlanilhaCusto> myList = new List<PlanilhaCusto>();

        public void Show()
        {
            myList.Add(new PlanilhaCusto(1, null, "Projetos", 0, 0));
            myList.Add(new PlanilhaCusto(2, 1, "Arquitetura", 5,10));
            myList.Add(new PlanilhaCusto(3, 1, "Estrutura", 0, 0));
            myList.Add(new PlanilhaCusto(4, 3, "Civil", 1, 50));
            myList.Add(new PlanilhaCusto(5, 3, "Infra", 3, 75));
            myList.Add(new PlanilhaCusto(6, null, "Pessoal", 0, 0));
            myList.Add(new PlanilhaCusto(7, 6, "Mão de Obra", 20, 5700));

            /*In this loop the value of the parent items must be updated
              (calculated). The hierarchy of the list can be unlimited,
              like a tree. I tried using a recursive method but I could
              not do it.*/
            foreach (var itemList in myList)
            {

            }
        }
    }
}
</code>```

答:
Assuming the Elements in the list are sorted the way they are in your example, the fastest way to do this should be to iterate through the list in reverse order and add the amount to the list entry with the correct id.

Iterate backwards through the list

When the current element has a parent add amount and amount*price to it

EDIT:

After reading your comment in your source, i assume you already knew what i just wrote.

My approach would be the following:

```<code>        for (int i = myList.Count - 1; i > 1; i--)
        {
            var temp = myList.ElementAt(i);
            if (temp.parentId != null)
            {
                var parent = myList.ElementAt(temp.parentId - 1);
                parent.amount += temp.amount;
                parent.price += (temp.amount * temp.price);
            }
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How to sum the value of child items from a hierarchical list in a loop.

I need that during the loop in the list the values of the amount and price property contain the sum of these properties of the children.

Below are the two classes to be used to help me solve my problem.

namespace SGP.Dto.Custo
{
    public class PlanilhaCusto
    {
        public int id{ get; set; }
        public int parenteId{ get; set; }
        public string name { get; set; }
        public decimal amount{ get; set; }
        public decimal price{ get; set; }

        public PlanilhaCusto(int pId, int pParenteId, pName, decimal pAmount, decimal pPrice)
        {
            id = pId;
            parentId = pParentId;
            name = pName;
            amount = pAmount;
            price = pPrice;
        }
    }
}

namespace SGP.Dto.Custo
{
    public class ShowList
    {
        List<Dto.Custo.PlanilhaCusto> myList = new List<PlanilhaCusto>();

        public void Show()
        {
            myList.Add(new PlanilhaCusto(1, null, "Projetos", 0, 0));
            myList.Add(new PlanilhaCusto(2, 1, "Arquitetura", 5,10));
            myList.Add(new PlanilhaCusto(3, 1, "Estrutura", 0, 0));
            myList.Add(new PlanilhaCusto(4, 3, "Civil", 1, 50));
            myList.Add(new PlanilhaCusto(5, 3, "Infra", 3, 75));
            myList.Add(new PlanilhaCusto(6, null, "Pessoal", 0, 0));
            myList.Add(new PlanilhaCusto(7, 6, "Mão de Obra", 20, 5700));

            /*In this loop the value of the parent items must be updated
              (calculated). The hierarchy of the list can be unlimited,
              like a tree. I tried using a recursive method but I could
              not do it.*/
            foreach (var itemList in myList)
            {

            }
        }
    }
}

Body:
Assuming the Elements in the list are sorted the way they are in your example, the fastest way to do this should be to iterate through the list in reverse order and add the amount to the list entry with the correct id.

Iterate backwards through the list

When the current element has a parent add amount and amount*price to it

EDIT:

After reading your comment in your source, i assume you already knew what i just wrote.

My approach would be the following:

        for (int i = myList.Count - 1; i > 1; i--)
        {
            var temp = myList.ElementAt(i);
            if (temp.parentId != null)
            {
                var parent = myList.ElementAt(temp.parentId - 1);
                parent.amount += temp.amount;
                parent.price += (temp.amount * temp.price);
            }
        }


问:
Get The Product Id of An Item If User Changes Quantity to 0 in WooCommerce Cart
I am trying to figure out a way to get the product ids of items that have their quantity reduced to 0 from the cart page.

I hook into the after woocommerce_after_cart_item_quantity_update which fires if user changes quantity to anything BUT 0. :(

```<code>function action_woocommerce_after_cart_item_quantity_update( $cart_item_key, $quantity, $old_quantity ) {
    var_error_log([$cart_item_key, $quantity, $old_quantity]);
};

add_action( 'woocommerce_after_cart_item_quantity_update', 'action_woocommerce_after_cart_item_quantity_update', 10, 3 );

function var_error_log( $object=null ){
    ob_start();                    // start buffer capture
    var_dump( $object );           // dump the values
    $contents = ob_get_contents(); // put the buffer into a variable
    ob_end_clean();                // end capture
    error_log( $contents );        // log contents of the result of var_dump( $object )
}
</code>```

Is there another way?

Edit:

Also the woocommerce_cart_item_removed hook is no good as it only runs when user clicks remove button, not when quantity for that item is changed to 0.

And the woocommerce_cart_item_removed hook occurs in a similar way to the woocommerce_cart_item_removed hook.

答:
Try this hook,

```<code>add_action( 'woocommerce_cart_item_removed', 'after_remove_product_from_cart', 10, 2 );
function after_remove_product_from_cart($removed_cart_item_key, $instance) {
    $line_item = $instance->removed_cart_contents[ $removed_cart_item_key ];
    $product_id = $line_item[ 'product_id' ];
}
</code>```

this will fire when an item is removed from the cart.
For more information,

woocommerce hook delete product from the cart

How to find out product id from “woocommerce_cart_item_removed” hook?

Hope this will helps you.

Body:
I am trying to figure out a way to get the product ids of items that have their quantity reduced to 0 from the cart page.

I hook into the after woocommerce_after_cart_item_quantity_update which fires if user changes quantity to anything BUT 0. :(

function action_woocommerce_after_cart_item_quantity_update( $cart_item_key, $quantity, $old_quantity ) {
    var_error_log([$cart_item_key, $quantity, $old_quantity]);
};

add_action( 'woocommerce_after_cart_item_quantity_update', 'action_woocommerce_after_cart_item_quantity_update', 10, 3 );

function var_error_log( $object=null ){
    ob_start();                    // start buffer capture
    var_dump( $object );           // dump the values
    $contents = ob_get_contents(); // put the buffer into a variable
    ob_end_clean();                // end capture
    error_log( $contents );        // log contents of the result of var_dump( $object )
}

Is there another way?

Edit:

Also the woocommerce_cart_item_removed hook is no good as it only runs when user clicks remove button, not when quantity for that item is changed to 0.

And the woocommerce_cart_item_removed hook occurs in a similar way to the woocommerce_cart_item_removed hook.

Body:
Try this hook,

add_action( 'woocommerce_cart_item_removed', 'after_remove_product_from_cart', 10, 2 );
function after_remove_product_from_cart($removed_cart_item_key, $instance) {
    $line_item = $instance->removed_cart_contents[ $removed_cart_item_key ];
    $product_id = $line_item[ 'product_id' ];
}

this will fire when an item is removed from the cart.
For more information,

woocommerce hook delete product from the cart

How to find out product id from “woocommerce_cart_item_removed” hook?

Hope this will helps you.


问:
Facebook Graph API: result in array or in json object
I have little bit confuse between graph api result.Can any one explain which default object method is facebook using when we fetch data via graph api. Have any application account setting for access data in json object or in array object, because some time i found user data in encrypted and some time non encrypted.
I found user email id in two way from facebook graph api.
One is:

```<code>{
   "id": "100001114785800",
   "name": "Stella Jackson",
   "first_name": "Stella",
   "last_name": "Jackson",
   "link": "http://www.facebook.com/profile.php?id=100001114785800",
   "birthday": "04/16/1987",
   "gender": "female",
   "email": "stella_ja@live.com",
   "timezone": 5.5,
   "locale": "en_US",
   "updated_time": "2010-10-08T13:26:10+0000"
}
</code>```

And second one is:

```<code>{
   "id": "100001114785800",
   "name": "Stella Jackson",
   "first_name": "Stella",
   "last_name": "Jackson",
   "link": "http://www.facebook.com/profile.php?id=100001114785800",
   "birthday": "04/16/1987",
   "gender": "female",
   "email": "stella_ja\u0040live.com",
   "timezone": 5.5,
   "locale": "en_US",
   "updated_time": "2010-10-08T13:26:10+0000"
}
</code>```

Have any idea?

Thanks

答:
The '\u0040' is same as obfuscated or Unicode form of '@' symbol. Most Parsers can convert that to the original symbol.

Check this for list of Unicode character set.

http://www.alanwood.net/demos/ansi.html

ContentLicense: CC BY-SA 2.5

Body:
I have little bit confuse between graph api result.Can any one explain which default object method is facebook using when we fetch data via graph api. Have any application account setting for access data in json object or in array object, because some time i found user data in encrypted and some time non encrypted.
I found user email id in two way from facebook graph api.
One is:

{
   "id": "100001114785800",
   "name": "Stella Jackson",
   "first_name": "Stella",
   "last_name": "Jackson",
   "link": "http://www.facebook.com/profile.php?id=100001114785800",
   "birthday": "04/16/1987",
   "gender": "female",
   "email": "stella_ja@live.com",
   "timezone": 5.5,
   "locale": "en_US",
   "updated_time": "2010-10-08T13:26:10+0000"
}

And second one is:

{
   "id": "100001114785800",
   "name": "Stella Jackson",
   "first_name": "Stella",
   "last_name": "Jackson",
   "link": "http://www.facebook.com/profile.php?id=100001114785800",
   "birthday": "04/16/1987",
   "gender": "female",
   "email": "stella_ja\u0040live.com",
   "timezone": 5.5,
   "locale": "en_US",
   "updated_time": "2010-10-08T13:26:10+0000"
}

Have any idea?

Thanks


问:
How to run tests from the command line ? (IntelliJ Idea + Java +TestNG)
I'm kind of new to Java and IntelliJ Environments

I managed to create a simple TestNG test inside IntelliJ (Only contains one assertion) and run it.

What are the ordered steps that I need to do in order to be able to run from the command line

I tried different approaches and nothing worked so far

Eventually I would like to run selenium but by now I'm OK with only running that simple assertion...

答:
From the official docs at http://testng.org/doc/documentation-main.html#running-testng

Assuming that you have TestNG in your class path, the simplest way to invoke TestNG is as follows:

```<code>java org.testng.TestNG testng1.xml
</code>```

Body:
From the official docs at http://testng.org/doc/documentation-main.html#running-testng

Assuming that you have TestNG in your class path, the simplest way to invoke TestNG is as follows:

java org.testng.TestNG testng1.xml


问:
any way to cache routes.php file in codeigniter?
i'm trying to add dynamic routes from database in CI. but my website is really slow after adding data into my table.

anyway to performed routes.php file? or anyway to speed up my site?

NOTE: i have more than 60,000 record for SEO friendly url.

routes affected my response server time, its about 4 seconds.

here is my code:

```<code>require_once(BASEPATH . 'database/DB' . EXT);
require_once(BASEPATH . 'helpers/url_helper' . EXT);
require_once(BASEPATH . 'helpers/text_helper' . EXT);
$db = &DB();

$query = $db->query('select id,title from news');
$result = $query->result();
foreach ($result as $row) {
    $string = strtolower(str_replace(' ', '-', $row->title));
    $route["funny-news/" . $string] = "news/newsDetails/$row->id";
}
</code>```

Thanks.

EDIT:

newsDetails Controller code:

```<code>public function newsDetails($id)
    {
        $hdata['active'] = "news";
        $result['news'] = $this->mytestdb->getNewsById($id);
        $this->load->view('nheader', $hdata);
        $this->load->view('newsDetails', $result);
        $this->load->view('footer');
    }
</code>```

答:
Open your routes.php and put the following line in

```<code>$route['funny-news/(.*)'] = "news/newsDetails/$1";
</code>```

And your controller should look like

```<code>public function newsDetails($slug)
{
    $hdata['active'] = "news";
    $result['news'] = $this->mytestdb->getNewsBySlug($slug);
    $this->load->view('nheader', $hdata);
    $this->load->view('newsDetails', $result);
    $this->load->view('footer');
}
</code>```

One thing - you should use an extra field in your db for your desired slug.

A function can be found here PHP function to make slug (URL string).

With this method you don't need to fill the DB with unnecessary routes.

Body:
i'm trying to add dynamic routes from database in CI. but my website is really slow after adding data into my table.

anyway to performed routes.php file? or anyway to speed up my site?

NOTE: i have more than 60,000 record for SEO friendly url.

routes affected my response server time, its about 4 seconds.

here is my code:

require_once(BASEPATH . 'database/DB' . EXT);
require_once(BASEPATH . 'helpers/url_helper' . EXT);
require_once(BASEPATH . 'helpers/text_helper' . EXT);
$db = &DB();

$query = $db->query('select id,title from news');
$result = $query->result();
foreach ($result as $row) {
    $string = strtolower(str_replace(' ', '-', $row->title));
    $route["funny-news/" . $string] = "news/newsDetails/$row->id";
}

Thanks.

EDIT:

newsDetails Controller code:

public function newsDetails($id)
    {
        $hdata['active'] = "news";
        $result['news'] = $this->mytestdb->getNewsById($id);
        $this->load->view('nheader', $hdata);
        $this->load->view('newsDetails', $result);
        $this->load->view('footer');
    }

Body:
Open your routes.php and put the following line in

$route['funny-news/(.*)'] = "news/newsDetails/$1";

And your controller should look like

public function newsDetails($slug)
{
    $hdata['active'] = "news";
    $result['news'] = $this->mytestdb->getNewsBySlug($slug);
    $this->load->view('nheader', $hdata);
    $this->load->view('newsDetails', $result);
    $this->load->view('footer');
}

One thing - you should use an extra field in your db for your desired slug.

A function can be found here PHP function to make slug (URL string).

With this method you don't need to fill the DB with unnecessary routes.


问:
Can I use Tarantool instead of Redis?
I'd like to use Tarantool to store data. How can I store data with TTL and simple logic (without the spaces)?

Like this:

```<code>box:setx(key, value, ttl);
box:get(key)
</code>```

答:
Yes, you can expire data in Tarantool and in a much more flexible way than in Redis. Though you can't do this without spaces, because space is a container for data in Tarantool (like database or table in other database systems).

In order to expire data, you have to install expirationd tarantool rock using tarantoolctl rocks install expirationd command. Full documentation on expirationd daemon can be found here.

Feel free to use a sample code below:

#!/usr/bin/env tarantool

package.path = './.rocks/share/tarantool/?.lua;' .. package.path

local fiber = require('fiber')
local expirationd = require('expirationd')

-- setup the database

box.cfg{}
box.once('init', function()
    box.schema.create_space('test')
    box.space.test:create_index('primary', {parts = {1, 'unsigned'}})
end)

-- print all fields of all tuples in a given space
local print_all = function(space_id)
    for _, v in ipairs(box.space[space_id]:select()) do
        local s = ''
        for i = 1, #v do s = s .. tostring(v[i]) .. '\t' end
        print(s)
    end
end

-- return true if tuple is more than 10 seconds old
local is_expired = function(args, tuple)
    return (fiber.time() - tuple[3]) > 10
end

-- simply delete a tuple from a space
local delete_tuple = function(space_id, args, tuple)
    box.space[space_id]:delete{tuple[1]}
end

local space = box.space.test

print('Inserting tuples...')

space:upsert({1, '0 seconds', fiber.time()}, {})
fiber.sleep(5)
space:upsert({2, '5 seconds', fiber.time()}, {})
fiber.sleep(5)
space:upsert({3, '10 seconds', fiber.time()}, {})

print('Tuples are ready:\n')

print_all('test')

print('\nStarting expiration daemon...\n')

-- start expiration daemon
-- in a production full_scan_time should be bigger than 1 sec
expirationd.start('expire_old_tuples', space.id, is_expired, {
    process_expired_tuple = delete_tuple, args = nil,
    tuples_per_iteration = 50, full_scan_time = 1
})

fiber.sleep(5)
print('\n\n5 seconds passed...')
print_all('test')

fiber.sleep(5)
print('\n\n10 seconds passed...')
print_all('test')

fiber.sleep(5)
print('\n\n15 seconds passed...')
print_all('test')

os.exit()
```

ContentLicense: CC BY-SA 4.0

Title: Can I use Tarantool instead of Redis?

Body:
I'd like to use Tarantool to store data. How can I store data with TTL and simple logic (without the spaces)?

Like this:

box:setx(key, value, ttl);
box:get(key)


问:
Laravel 5.2 validate existence of array values
Using Laravel, I have the following $header array:

```<code>[0] => var1
[1] => var2
[2] => var3
[3] => ...
</code>```

And I need to validate that each of the values exist. Is there a more efficient way than

```<code>if (in_array('var1', $header) && in_array('var2', $header)...
</code>```

I have 15 of these to check for as part of columns in a CSV file import.

Thanks

答:
I did it like this:</p>

```<code>$intersect = array_intersect($expectedCSVHeader, $headerRow->toArray());

if (count($intersect) != count($expectedCSVHeader)) {
    throw new Exception('Column names missing from template. Please repair the CSV file and upload it again');
}
</code>```

Body:
Using Laravel, I have the following $header array:

[0] => var1
[1] => var2
[2] => var3
[3] => ...

And I need to validate that each of the values exist. Is there a more efficient way than

if (in_array('var1', $header) && in_array('var2', $header)...

I have 15 of these to check for as part of columns in a CSV file import.

Thanks

Body:
I did it like this:

$intersect = array_intersect($expectedCSVHeader, $headerRow->toArray());

if (count($intersect) != count($expectedCSVHeader)) {
    throw new Exception('Column names missing from template. Please repair the CSV file and upload it again');
}


问:
How to make pane and elements in it resizable when stage size is changing
Can you please tell me how can I realize that the whole content of a pane will be resized while the stage is resized with mousedragg. Here is my code:

```<code>public class fab extends Application {
private Stage stage;
private Pane pane;
private Scene scene;

@Override
public void start(Stage stage) throws Exception {

this.stage = stage;

Button button = new Button("Button");

pane = new Pane();
pane.getChildren().add(button);

stage.setTitle("Test");
scene = new Scene(pane, 640, 640);
stage.setScene(scene);
stage.show();

}

public static void main(String[] args) {
    launch(args);
}
</code>```

I think there is the idea of binding. But I don't know how to use that, in order  to make all nodes of a pane resizable, when the stage size is changing.

I'm searching a solution without Fxml or sceneBuilder.

Thank you in advance.

答:
Here is the solution if you wish to bind the width of the button to you scene width

```<code>button.minWidthProperty().bind(scene.widthProperty());
</code>```

You can also modify this +/- whatever you want for ex

```<code>button.minWidthProperty().bind(scene.widthProperty().subtract(20));
</code>```

and you can do the same for the height

```<code>button.minHeightProperty().bind(scene.heightProperty().subtract(200));
</code>```

Body:
Can you please tell me how can I realize that the whole content of a pane will be resized while the stage is resized with mousedragg. Here is my code:

public class fab extends Application {
private Stage stage;
private Pane pane;
private Scene scene;

@Override
public void start(Stage stage) throws Exception {

this.stage = stage;

Button button = new Button("Button");

pane = new Pane();
pane.getChildren().add(button);

stage.setTitle("Test");
scene = new Scene(pane, 640, 640);
stage.setScene(scene);
stage.show();

}

public static void main(String[] args) {
    launch(args);
}

I think there is the idea of binding. But I don't know how to use that, in order  to make all nodes of a pane resizable, when the stage size is changing.

I'm searching a solution without Fxml or sceneBuilder.

Thank you in advance.

Body:
Here is the solution if you wish to bind the width of the button to you scene width

button.minWidthProperty().bind(scene.widthProperty());

You can also modify this +/- whatever you want for ex

button.minWidthProperty().bind(scene.widthProperty().subtract(20));

and you can do the same for the height

button.minHeightProperty().bind(scene.heightProperty().subtract(200));


问:
How do I migrate DNS from DO to Route 53
I'd like to move our DNS management from DO to AWS.

I've updated the DNS on the DO to point to AWS Route 53 nameservers and added the records on route 53 in preparation.

After setting the NS records for the domain, it seems like it hasn't yet propagated. My experience has been that DNS changes typically take a couple of minutes, unless I've made a mistake somewhere (albeit often it's said that it can take between 24-48 hours).

After running some dig commands, it seems like the NS records are still pointing to digital ocean.

Should I have made additional changes to get this to work?

答: Where is your domain "registered"? You'll probably want to change the NS records in Route53 (as it seems like you've done already), but you'll also need to change them with your domain registrar who ultimately defines your name servers. So, if it's registered in Route53, then you'll need to go in to Route53 -> Registered domains and you'll see "Name servers" in there - they'll be pointing to your old name servers I suspect. If it's not Route53 where you've got your domain registered, it'll be a similar process whether your domain is registered with Gandi, GoDaddy, 1&1, eNom or wherever.</p>


问:
JGroups 'cannot find symbol'
I'm running through the tutorial from this link (page 16) but when I compile the source files, I get about 30 'cannot find symbol' errors.

I have the JGroups .jar file in the directory and I'm compiling with the command: javac -cp ".;jgroups-4.0.8.Final.jar" *.java but to no avail.

Can anyone help me to get JGroups working?

答:
If not all java files are on the same directory level and you reference any java classes in your sources from . then they won't be found.
You would need to use something like ./**/*.java to include all java classes recuresively.
This will even only work as long as all dependent classes are also packed within the jroups.jar file.
My suggestion is to setup a maven project where you add jgroups as dependency. In this case all subdependencies are automatically loaded. </p>

Title: JGroups 'cannot find symbol'


问:
XPath axis, get all following nodes until
I have the following example of HTML:

```<code><!-- lots of html -->
<h2>Foo bar</h2>
<p>lorem</p>
<p>ipsum</p>
<p>etc</p>

<h2>Bar baz</h2>
<p>dum dum dum</p>
<p>poopfiddles</p>
<!-- lots more html ... -->
</code>```

I'm looking to extract all paragraphs following the 'Foo bar' header, until I reach the 'Bar baz' header (the text for the 'Bar baz' header is unknown, so unfortunately I can't use the answer provided by bougyman). Now I can of course using something like //h2[text()='Foo bar']/following::p but that of course will grab all paragraphs following this header. So I have the option to traverse the nodeset and push paragraphs into an Array until the text matches that of the next following header, but let's be honest, that's never as cool as being able to do it in XPath.

Is there a way to do this that I'm missing?

答: XPath 2.0 has the operator << (with $node1 << $node2 being true if $node1 precedes $node2) so that way you can use //h2[. = 'Foo bar']/following-sibling::p[. << //h2[. = 'Bar baz']]. I don't know however what nokogiri is respectively whether it supports XPath 2.0.

Body:
I have the following example of HTML:

Foo bar

lorem

ipsum

etc

Bar baz

dum dum dum

poopfiddles

I'm looking to extract all paragraphs following the 'Foo bar' header, until I reach the 'Bar baz' header (the text for the 'Bar baz' header is unknown, so unfortunately I can't use the answer provided by bougyman). Now I can of course using something like //h2[text()='Foo bar']/following::p but that of course will grab all paragraphs following this header. So I have the option to traverse the nodeset and push paragraphs into an Array until the text matches that of the next following header, but let's be honest, that's never as cool as being able to do it in XPath.

Is there a way to do this that I'm missing?


问:
How to unmarshall JSON object with multiple value types
Say I have an object:

```<code>{
  "name": "joe",
  "age": 60
}
</code>```

How to unmarshall it into a Map[String, String] type?

答:
The JsObject class has a fields parameter that is a Map[String, JsValue]. If you want a Map[String, String], use mapValues:

```<code>import spray.json._
import DefaultJsonProtocol._

val json =
  """{
       "name": "joe",
       "age": 60
     }"""

val jsObj = json.parseJson.asJsObject // JsObject
val myMap: Map[String, String] = jsObj.fields.mapValues(_.toString)

println(myMap)
// Map(name -> "joe", age -> 60)
</code>```

Body:
Say I have an object:

{
  "name": "joe",
  "age": 60
}

How to unmarshall it into a Map[String, String] type?

Body:
The JsObject class has a fields parameter that is a Map[String, JsValue]. If you want a Map[String, String], use mapValues:

import spray.json._
import DefaultJsonProtocol._

val json =
  """{
       "name": "joe",
       "age": 60
     }"""

val jsObj = json.parseJson.asJsObject // JsObject
val myMap: Map[String, String] = jsObj.fields.mapValues(_.toString)

println(myMap)
// Map(name -> "joe", age -> 60)


问:
publishing an app flavor as a single app
i have created two flavor of app using following in gradle

```<code>defaultConfig {
    applicationId "com.example.myapp"
}

productFlavors
{

free {

    versionName "1.0-free"
    buildConfigField "boolean", "PAID_VERSION", "false"
    buildConfigField "String", "BuildType", "Free"
}
paid {
    versionName "1.0-paid"
    buildConfigField "boolean", "PAID_VERSION", "true"
    buildConfigField "String", "BuildType", "Paid"
}
}
</code>```

and in java using like this

```<code>public void manageFeaturesWithBuildType()
    {
        String buildType = BuildConfig.BuildType;
        if(buildType.equals("Paid"))
        {
            //Here Enable or Disable your features for paid Build
        }
        else
        {
            //Here Enable or Disable your features for free Build
        }
    }
</code>```

now i created a signed apk for both free-relese.apk and paid-release.apk

i want to publish it on playstore

i want to make it as both paid and free versions

how can i publish it?

Do I need to publish paid-release apk or free-release.apk or both?

答:
You'll need to specify two different applicationId for each flavors if you like to have the paid version to be separate from your free version.

```<code>free {
   applicationId "com.example.myapp.free"
}
</code>```

&

```<code>paid {
   applicationId "com.example.myapp.paid"
}
</code>```

or you could simplify above with using applicationIdSuffix ".free" and remove applicationId from the flavors

Body:
i have created two flavor of app using following in gradle

defaultConfig {
    applicationId "com.example.myapp"
}

productFlavors
{

free {

    versionName "1.0-free"
    buildConfigField "boolean", "PAID_VERSION", "false"
    buildConfigField "String", "BuildType", "Free"
}
paid {
    versionName "1.0-paid"
    buildConfigField "boolean", "PAID_VERSION", "true"
    buildConfigField "String", "BuildType", "Paid"
}
}

and in java using like this

public void manageFeaturesWithBuildType()
    {
        String buildType = BuildConfig.BuildType;
        if(buildType.equals("Paid"))
        {
            //Here Enable or Disable your features for paid Build
        }
        else
        {
            //Here Enable or Disable your features for free Build
        }
    }

now i created a signed apk for both free-relese.apk and paid-release.apk

i want to publish it on playstore

i want to make it as both paid and free versions

how can i publish it?

Do I need to publish paid-release apk or free-release.apk or both?

Body:
You'll need to specify two different applicationId for each flavors if you like to have the paid version to be separate from your free version.

free {
   applicationId "com.example.myapp.free"
}

&

paid {
   applicationId "com.example.myapp.paid"
}

or you could simplify above with using applicationIdSuffix ".free" and remove applicationId from the flavors


问:
Text based memory game | No clue how to make it restart
Alright, so I'm using Python 3.4.3. I'm taking an entry level course for Python, and we're supposed to make a game. I've tried the search function for my problem but all of these answers are too confusing to me. I'm a Networking major so this is my first time ever messing around with code of any sort.

Basically, I'm making a text based memory game. There's 11 questions and they can type "y" for yes or anything else for no. When someone types in the wrong answer I want it to be so it goes back to the beginning of the game. I'm also trying to figure out how to add a way for the player to exit the game when they're finished besides just closing out of Python. I underestimated how difficult this would be for me and the project is due tonight at midnight (I'm cutting this pretty closely I know).

Here are the first few lines of my game:

```<code># Game Introduction (Everything works, but it's unfinished and I still need to figure out how to restart the game when someone responds with the wrong question.)

print ('Welcome to The Dampest Dungeon. Try to stay alive!')

print (' ')

# When they first wake up.

print ('You awake in a damp dungeon. You see a door. Do you open the door?')
def dampest_dung():
   def function(y):
    return "y"
print ("testers")
game_resp = input('Type y for yes or n for no:')

print ('')

if game_resp=='y':
    print ("The door won't budge. You push harder and it falls on top of you. Game over.")
else:
    print ("Instead, you look under a rug and find a rusty key.")
print (' ')
# Second question where they can try the key.

print ('Will you try to use the rusty key on the door?')
gameresptwo = input('Type y for yes or n for no:')

print (' ')

if gameresptwo=='y':
    print ("The door opens noisily when you attempt to use the key.")
else:
    print ("You stand in the room without doing anything. Nothing happens. Eventually, you starve. Game over.")
</code>```

You can see that there's only two options. If they choose the wrong one I want the game to restart. To say I'm a novice with Python or programming in general would be an understatement. I'm not trying to be fancy here. I'm looking for the simplest solution possible. Thank you very much!

I'm trying to define some functions so the game restarts but I can't get anything to work. Ughhh I'm so bad

答:
I suggest you put your game into a function.

If you like the input you are receiving : you would be continuing to the end of your function, and in the end, if you like all the answers : it would return True.
If you dont like a single answer : the function would return False.

Then, you would have a loop encapsulating your function.
And, according to the output of your function (True or False) : you would either recompute your game, or end it.

I'm giving you an example as you tried something :

```<code>def my_game():
    ans_1 = input("My first question :"):
    if I_like_the_answer:
        print "You're good to go !"
    else:
        print "I'm sorry. You lose !"
        return False

    #   ...

    #   End of game.
    return True

#   Game is still not completed at this point.
my_game_results = False
while my_game_results is False:
    my_game_results = my_game()

print "You beat the game!"
</code>```

Body:
Alright, so I'm using Python 3.4.3. I'm taking an entry level course for Python, and we're supposed to make a game. I've tried the search function for my problem but all of these answers are too confusing to me. I'm a Networking major so this is my first time ever messing around with code of any sort.

Basically, I'm making a text based memory game. There's 11 questions and they can type "y" for yes or anything else for no. When someone types in the wrong answer I want it to be so it goes back to the beginning of the game. I'm also trying to figure out how to add a way for the player to exit the game when they're finished besides just closing out of Python. I underestimated how difficult this would be for me and the project is due tonight at midnight (I'm cutting this pretty closely I know).

Here are the first few lines of my game:

# Game Introduction (Everything works, but it's unfinished and I still need to figure out how to restart the game when someone responds with the wrong question.)

print ('Welcome to The Dampest Dungeon. Try to stay alive!')

print (' ')

# When they first wake up.

print ('You awake in a damp dungeon. You see a door. Do you open the door?')
def dampest_dung():
   def function(y):
    return "y"
print ("testers")
game_resp = input('Type y for yes or n for no:')

print ('')

if game_resp=='y':
    print ("The door won't budge. You push harder and it falls on top of you. Game over.")
else:
    print ("Instead, you look under a rug and find a rusty key.")
print (' ')
# Second question where they can try the key.

print ('Will you try to use the rusty key on the door?')
gameresptwo = input('Type y for yes or n for no:')

print (' ')

if gameresptwo=='y':
    print ("The door opens noisily when you attempt to use the key.")
else:
    print ("You stand in the room without doing anything. Nothing happens. Eventually, you starve. Game over.")

You can see that there's only two options. If they choose the wrong one I want the game to restart. To say I'm a novice with Python or programming in general would be an understatement. I'm not trying to be fancy here. I'm looking for the simplest solution possible. Thank you very much!

I'm trying to define some functions so the game restarts but I can't get anything to work. Ughhh I'm so bad

Body:
I suggest you put your game into a function.

If you like the input you are receiving : you would be continuing to the end of your function, and in the end, if you like all the answers : it would return True.
If you dont like a single answer : the function would return False.

Then, you would have a loop encapsulating your function.
And, according to the output of your function (True or False) : you would either recompute your game, or end it.

I'm giving you an example as you tried something :

def my_game():
    ans_1 = input("My first question :"):
    if I_like_the_answer:
        print "You're good to go !"
    else:
        print "I'm sorry. You lose !"
        return False

    #   ...

    #   End of game.
    return True

#   Game is still not completed at this point.
my_game_results = False
while my_game_results is False:
    my_game_results = my_game()

print "You beat the game!"


问:
How to cut uuid in golang?
In order to make semi-random slugs, I'd like to use first 8 characters of uuid. So I have

```<code>import (
    fmt
    "github.com/satori/go.uuid"
)

    u1 := uuid.NewV4()
    fmt.Println("u1 :", u1)

    runes := []rune(u1)
    slug := string(runes[0:7])
</code>```

But in compile time I get this error:

cannot convert u1 (type uuid.UUID) to type []rune

How can I fix it?

答:
In that package (I just looked at the source code) a UUID is an alias for [16]byte, so you cannot concert it to a rune array, not that you want to.

Try this:

```<code>s := hex.EncodeToString(u1.Bytes()[:4])
</code>```

This will give you 8 hex digits. However, this is still a roundabout way of doing things. A v4 UUID is random except for certain bits, so if you are not using the whole UUID it is more straightforward to just generate 4 random bytes. Use the Read() function in math/rand (which must be seeded) or crypto/rand (which is what the UUID library uses).

```<code>b := make([]byte, 4)
rand.Read(b) // Doesn’t actually fail
s := hex.EncodeToString(b)
</code>```

Title: How to cut uuid in golang?

Body:
In order to make semi-random slugs, I'd like to use first 8 characters of uuid. So I have

import (
    fmt
    "github.com/satori/go.uuid"
)

    u1 := uuid.NewV4()
    fmt.Println("u1 :", u1)

    runes := []rune(u1)
    slug := string(runes[0:7])

But in compile time I get this error:

cannot convert u1 (type uuid.UUID) to type []rune

How can I fix it?

Body:
In that package (I just looked at the source code) a UUID is an alias for [16]byte, so you cannot concert it to a rune array, not that you want to.

Try this:

s := hex.EncodeToString(u1.Bytes()[:4])

This will give you 8 hex digits. However, this is still a roundabout way of doing things. A v4 UUID is random except for certain bits, so if you are not using the whole UUID it is more straightforward to just generate 4 random bytes. Use the Read() function in math/rand (which must be seeded) or crypto/rand (which is what the UUID library uses).

b := make([]byte, 4)
rand.Read(b) // Doesn’t actually fail
s := hex.EncodeToString(b)


问:
Receive data via url Get
I am trying to receive data via url, but I have this question of how to receive this url

```<code>localhost:8080/?action&p[4]=2&p[7]=5&p[12]=0&p[15]=1
</code>```

I need the values of

```<code>[2] = 4

2
and
4
</code>```

答:
Below code can help you getting all data of p variable and the data enclosed within [] from URL (Tested Offline):

```<code><?php
$url = "localhost:8080/?action&p[4]=2&p[7]=5&p[12]=0&p[15]=1";

$arr = explode("&",$url);

foreach(array_slice($arr,1) as $key=>$value)
{

$valArr = explode("=",$value);

$valArr[0] = str_replace("p[","",$valArr[0]);
$valArr[0] = str_replace("]","",$valArr[0]);
echo "Value 1: ". $valArr[0];
echo "<br>";
echo "Value 2: ".$valArr[1];
echo "<br>";
}

//  Below Output will come:
Value 1: 4
Value 2: 2
Value 1: 7
Value 2: 5
Value 1: 12
Value 2: 0
Value 1: 15
Value 2: 1

?>
</code>```

You will get both the values as required but please make sure that URL structure remains the same.

There might be better solution to resolve your issue but the one I have given is also correct.

Title: Receive data via url Get

Body:
I am trying to receive data via url, but I have this question of how to receive this url

localhost:8080/?action&p[4]=2&p[7]=5&p[12]=0&p[15]=1

I need the values of

[2] = 4

2
and
4

Body:
Below code can help you getting all data of p variable and the data enclosed within [] from URL (Tested Offline):

<?php
$url = "localhost:8080/?action&p[4]=2&p[7]=5&p[12]=0&p[15]=1";

$arr = explode("&",$url);

foreach(array_slice($arr,1) as $key=>$value)
{

$valArr = explode("=",$value);

$valArr[0] = str_replace("p[","",$valArr[0]);
$valArr[0] = str_replace("]","",$valArr[0]);
echo "Value 1: ". $valArr[0];
echo "<br>";
echo "Value 2: ".$valArr[1];
echo "<br>";
}

//  Below Output will come:
Value 1: 4
Value 2: 2
Value 1: 7
Value 2: 5
Value 1: 12
Value 2: 0
Value 1: 15
Value 2: 1

?>

You will get both the values as required but please make sure that URL structure remains the same.

There might be better solution to resolve your issue but the one I have given is also correct.


问:
how to set next token to its corresponding jtextfeild
I am reading a CSV file token by token so that each  token belong to a jtextfeild how to do because it shows last token in jtextfeild</p>

```<code>while(st.hasMoreTokens()){
//display csv values
 String setText= st.nextToken();// here what should I do that each JTextFeild get next token;
 ModTxt.setText();
 MinSpeedTxt.setText();
 MaxSpeedTxt.setText();
</code>```

答:
You need to call nextToken() to get the next field in your CSV string and set it in your textfield.

```<code> ModTxt.setText(st.nextToken());
 MinSpeedTxt.setText(st.nextToken());
 MaxSpeedTxt.setText(st.nextToken());
</code>```

Body:
I am reading a CSV file token by token so that each  token belong to a jtextfeild how to do because it shows last token in jtextfeild

while(st.hasMoreTokens()){
//display csv values
 String setText= st.nextToken();// here what should I do that each JTextFeild get next token;
 ModTxt.setText();
 MinSpeedTxt.setText();
 MaxSpeedTxt.setText();

Body:
You need to call nextToken() to get the next field in your CSV string and set it in your textfield.

 ModTxt.setText(st.nextToken());
 MinSpeedTxt.setText(st.nextToken());
 MaxSpeedTxt.setText(st.nextToken());


问:
php curl not working in localhost
Manually installed php. But curl not working.
Settings

```<code>;extension=php_bz2.dll
    extension=php_curl.dll
    extension=php_fileinfo.dll
    extension=php_gd2.dll
   ;extension=php_gettext.dll
</code>```

my code:

```<code>if  (in_array  ('curl', get_loaded_extensions())) {

        echo "CURL is available on your web server";

    }  else {
        echo "CURL is not available on your web server";
    }
?>
</code>```

Ans:
CURL is not available on your web server

答:
Here are the steps from obtaining PHP to enabling cURL:

Download PHP (these steps tested with 7.1)
Add PHP folder to PATH environment variable
Update php.ini file with absolute path for extension directory and uncomment php_curl.dll and php_openssl.dll extensions
Update httpd.conf (Apache config file) to load php7apache2_4.dll module in PHP folder and set PHPIniDir to PHP directory
Copy libeay32.dll libssh2.dll and ssleay32.dll into apache/bin (replace existing)
Restart Apache.

Enable cURL on PHP7 windows10 64 bit Apache 2.4

Title: php curl not working in localhost

Body:
Manually installed php. But curl not working.
Settings

;extension=php_bz2.dll
    extension=php_curl.dll
    extension=php_fileinfo.dll
    extension=php_gd2.dll
   ;extension=php_gettext.dll

my code:

if  (in_array  ('curl', get_loaded_extensions())) {

        echo "CURL is available on your web server";

    }  else {
        echo "CURL is not available on your web server";
    }
?>

Ans:
CURL is not available on your web server


问:
Google Protobuf , .proto file query
I need to create .proto file for following CRMData case class.
I am having confusion with the following datatypes i.e Nested Maps and user defined class (ShipToGroup)</p>

```<code>case class CRMData(
       var customerShipToGroups : Map[String, Map[UUID, ShipToGroup]],
       var shipToGroups : Map[UUID, ShipToGroup],
       var shipToGroupLastUsed : UUID,
       var defaultShipToGroup : UUID
)

case class ShipToGroup(
    var customerUUID : String,
    var shipToGroupUUID : UUID,
    var name : String,
    var address : String,
    var companyName : String,
    var phoneNumber : Long,
    var city : String,
    var state : String,
    var zip : Int,
    var country : String,
    var landmark : String,
    var addressType : Int,
    var emailId : String,
    var addedAsBillingAddress : Boolean,
    var usedAsBillingAddress: Boolean,
    var isDefault : Boolean,
    var address2 : String)
</code>```

答:
The biggest problem you're going to have is that guids (I assume that is what UUID is) aren't a primitive type in .proto, and map<,> in .proto only works with string and integer types. I'm going to assume you're happy to use string as the closest match (and because it works in maps).

You can't do nested maps, but you can have a map where each element is something that has a map.

Combine those two caveats, and you can do something like:

```<code>syntax = "proto3";
message CRMData {
    map<string, NeedAGoodName> customerShipToGroups = 1;
    map<string, ShipToGroup> shipToGroups = 2;
    string shipToGroupLastUsed = 3;
    string defaultShipToGroup = 4;
}
message NeedAGoodName {
    map<string, ShipToGroup> items = 1;
}
message ShipToGroup {
    string customerUUID = 1;
    string shipToGroupUUID = 2;
    // ...
    string address2 = 17;
}
</code>```

Note: it might look like I'm using string throughout, but that's just because of the specific example; .proto supports more primitives than that - I would expect to see some bool and uint32 in your final version. Maybe some fixed64 for the phone number, although a string might be more common for that. You might also want an enum for the addressType.

Title: Google Protobuf , .proto file query

Body:
I need to create .proto file for following CRMData case class.
I am having confusion with the following datatypes i.e Nested Maps and user defined class (ShipToGroup)

case class CRMData(
       var customerShipToGroups : Map[String, Map[UUID, ShipToGroup]],
       var shipToGroups : Map[UUID, ShipToGroup],
       var shipToGroupLastUsed : UUID,
       var defaultShipToGroup : UUID
)

case class ShipToGroup(
    var customerUUID : String,
    var shipToGroupUUID : UUID,
    var name : String,
    var address : String,
    var companyName : String,
    var phoneNumber : Long,
    var city : String,
    var state : String,
    var zip : Int,
    var country : String,
    var landmark : String,
    var addressType : Int,
    var emailId : String,
    var addedAsBillingAddress : Boolean,
    var usedAsBillingAddress: Boolean,
    var isDefault : Boolean,
    var address2 : String)

Body:
The biggest problem you're going to have is that guids (I assume that is what UUID is) aren't a primitive type in .proto, and map<,> in .proto only works with string and integer types. I'm going to assume you're happy to use string as the closest match (and because it works in maps).

You can't do nested maps, but you can have a map where each element is something that has a map.

Combine those two caveats, and you can do something like:

syntax = "proto3";
message CRMData {
    map<string, NeedAGoodName> customerShipToGroups = 1;
    map<string, ShipToGroup> shipToGroups = 2;
    string shipToGroupLastUsed = 3;
    string defaultShipToGroup = 4;
}
message NeedAGoodName {
    map<string, ShipToGroup> items = 1;
}
message ShipToGroup {
    string customerUUID = 1;
    string shipToGroupUUID = 2;
    // ...
    string address2 = 17;
}

Note: it might look like I'm using string throughout, but that's just because of the specific example; .proto supports more primitives than that - I would expect to see some bool and uint32 in your final version. Maybe some fixed64 for the phone number, although a string might be more common for that. You might also want an enum for the addressType.


问:
how to programatically theme an activity to be like a dialog?

Question

How does one programatically (without touching the AndroidManifext.xml) set the theme of an Activity so that it looks like a dialog?

Note: I am ok with modifying the AndroidManifext.xml as long as it does not need to be modified in order to switch between making it look like a normal activity or a dialog.

What I've tried so far

I tried the following as per this stackoverflow answer:

```<code>public class DialogActivity extends Activity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        setTheme(android.R.style.Theme_DeviceDefault_Dialog);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialog);
        Log.d(TAG,"Build.VERSION.SDK_INT: "+Build.VERSION.SDK_INT); // 23
    }
}
</code>```

But it ends up blacking out everything in the background.

I also saw this stackoverflow answer, and tried:

```<code>public class DialogActivity extends Activity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        setTheme(android.R.style.Theme_DeviceDefault_Dialog);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialog);
        getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
    }
}
</code>```

but it ends up making everything black.

What do? Thank you.

答:
Try these code before dailog.setMessage(...);

```<code>Dialog id  = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_DARK);

Dialog ID = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);

//Default theme
</code>```

Try this for Old theme
     Dialog ID = new AlertDialog.Builder(this,AlertDialog.THEME_TRADITIONAL);

Try these for KITKAT theme

```<code>Dialog ID = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_DARK); //Dark

Dialog ID = new AlertDialog.Builder(this,AlertDialog.THEME_HOLO_LIGHT);
</code>```

Try these codes for Pragmatically

Exmaple

```<code>    dialog = new AlertDialog.Builder(this);
            dialog = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_DARK);
            dialog.setTitle("HAI");
            dialog.setMessage("look");
            dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
Toast toast= Toast.makeText(getApplicationContext(), "This is exmaple theme", Toast.LENGTH_LONG);
</code>```

Body:
Question

How does one programatically (without touching the AndroidManifext.xml) set the theme of an Activity so that it looks like a dialog?

Note: I am ok with modifying the AndroidManifext.xml as long as it does not need to be modified in order to switch between making it look like a normal activity or a dialog.

What I've tried so far

I tried the following as per this stackoverflow answer:

public class DialogActivity extends Activity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        setTheme(android.R.style.Theme_DeviceDefault_Dialog);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialog);
        Log.d(TAG,"Build.VERSION.SDK_INT: "+Build.VERSION.SDK_INT); // 23
    }
}

But it ends up blacking out everything in the background.

I also saw this stackoverflow answer, and tried:

public class DialogActivity extends Activity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        setTheme(android.R.style.Theme_DeviceDefault_Dialog);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialog);
        getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
    }
}

but it ends up making everything black.

What do? Thank you.

Body:
Try these code before dailog.setMessage(...);

Dialog id  = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_DARK);

Dialog ID = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);

//Default theme

Try this for Old theme
     Dialog ID = new AlertDialog.Builder(this,AlertDialog.THEME_TRADITIONAL);

Try these for KITKAT theme

Dialog ID = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_DARK); //Dark

Dialog ID = new AlertDialog.Builder(this,AlertDialog.THEME_HOLO_LIGHT);

Try these codes for Pragmatically

Exmaple

    dialog = new AlertDialog.Builder(this);
            dialog = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_DARK);
            dialog.setTitle("HAI");
            dialog.setMessage("look");
            dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
Toast toast= Toast.makeText(getApplicationContext(), "This is exmaple theme", Toast.LENGTH_LONG);


问:
ASP .NET MVC + Submit + JSON
I need to send Model data and JSON data in one request. What does it mean:

If i send JSON data with this function:

```<code>    $("#SaveOrder").click(function () {
        $.ajax({
            url: '/Manager/AddOrder',
            type: 'POST',
            dataType: 'json',
            data: $.toJSON(ResultArray),
            contentType: 'application/json; charset=utf-8'
        });
    });
</code>```

i have

public ActionResult AddOrder(SUPNew.Models.Order newOrder, List<OrderList> ResultArray)

```<code>SUPNew.Models.Order newOrder = null
List<OrderList> ResultArray = not null
</code>```

but if i send request with <input type="submit"> i have

```<code>SUPNew.Models.Order newOrder = not null
List<OrderList> ResultArray = null
</code>```

How can i send jQuery array (JSON data) and SUPNew.Models.Order in one request?

Content of ResultArray- $.toJSON(ResultArray), where ResultArray is jQuery array like:

```<code>var CurrentOrder =
            [{
                'ProviderAn': $("#DdlProviders").val(),
                'ItemAn': $("#DdlItems").val()
            }];
</code>```

And this is MVC 2

答:
Don't forget to set the request content type:

```<code>$('#SaveOrder').click(function () {
    $.ajax({
        url: '/Manager/AddOrder',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify({
            newOrder: { orderProp1: 'value1', orderProp2: 'value2' },
            resultArray: [
                { orderListProp1: 'value1', orderListProp2: 'value2' },
                { orderListProp1: 'value3', orderListProp2: 'value4' },
                { orderListProp1: 'value5', orderListProp2: 'value6' }
            ]
        }),
        contentType: 'application/json; charset=utf-8',
        success: function(result) {
            // the request succeeded
        }
    });

    // Don't forget to cancel the default action or if SaveOrder
    // is some link you might get redirected before the
    // AJAX call ever had time to execute
    return false;
});
</code>```

Now on the server side you might need a new view model which will aggregate those two objects:

```<code>public class MyViewModel
{
    public Order NewOrder { get; set; }
    public List<OrderList> ResultArray { get; set; }
}
</code>```

and have:

```<code>[HttpPost]
public ActionResult AddOrder(MyViewModel model)
{
    ...
}
</code>```

Also on the server side unless you are using ASP.NET 3.0 which supports JSON by default you need to write a custom handler capable of parsing it.

UPDATE:

You could use the following to serialize the form as JSON:

```<code>$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
</code>```

and then:

```<code>$.ajax({
    url: '/Manager/AddOrder',
    contentType: 'application/json',
    type: 'POST',
    dataType: 'json',
    data: JSON.stringify({
        newOrder: $('#SaveOrder').serializeObject(),
        resultArray: [
            { orderListProp1: 'value1', orderListProp2: 'value2' },
            { orderListProp1: 'value3', orderListProp2: 'value4' },
            { orderListProp1: 'value5', orderListProp2: 'value6' }
        ]
    }),
    contentType: 'application/json; charset=utf-8'
});
</code>```

Title: ASP .NET MVC + Submit + JSON

Body:
I need to send Model data and JSON data in one request. What does it mean:

If i send JSON data with this function:

    $("#SaveOrder").click(function () {
        $.ajax({
            url: '/Manager/AddOrder',
            type: 'POST',
            dataType: 'json',
            data: $.toJSON(ResultArray),
            contentType: 'application/json; charset=utf-8'
        });
    });

i have

public ActionResult AddOrder(SUPNew.Models.Order newOrder, List<OrderList> ResultArray)

SUPNew.Models.Order newOrder = null
List<OrderList> ResultArray = not null

but if i send request with <input type="submit"> i have

SUPNew.Models.Order newOrder = not null
List<OrderList> ResultArray = null

How can i send jQuery array (JSON data) and SUPNew.Models.Order in one request?

Content of ResultArray- $.toJSON(ResultArray), where ResultArray is jQuery array like:

var CurrentOrder =
            [{
                'ProviderAn': $("#DdlProviders").val(),
                'ItemAn': $("#DdlItems").val()
            }];

And this is MVC 2

Body:
Don't forget to set the request content type:

$('#SaveOrder').click(function () {
    $.ajax({
        url: '/Manager/AddOrder',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify({
            newOrder: { orderProp1: 'value1', orderProp2: 'value2' },
            resultArray: [
                { orderListProp1: 'value1', orderListProp2: 'value2' },
                { orderListProp1: 'value3', orderListProp2: 'value4' },
                { orderListProp1: 'value5', orderListProp2: 'value6' }
            ]
        }),
        contentType: 'application/json; charset=utf-8',
        success: function(result) {
            // the request succeeded
        }
    });

    // Don't forget to cancel the default action or if SaveOrder
    // is some link you might get redirected before the
    // AJAX call ever had time to execute
    return false;
});

Now on the server side you might need a new view model which will aggregate those two objects:

public class MyViewModel
{
    public Order NewOrder { get; set; }
    public List<OrderList> ResultArray { get; set; }
}

and have:

[HttpPost]
public ActionResult AddOrder(MyViewModel model)
{
    ...
}

Also on the server side unless you are using ASP.NET 3.0 which supports JSON by default you need to write a custom handler capable of parsing it.

UPDATE:

You could use the following to serialize the form as JSON:

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

and then:

$.ajax({
    url: '/Manager/AddOrder',
    contentType: 'application/json',
    type: 'POST',
    dataType: 'json',
    data: JSON.stringify({
        newOrder: $('#SaveOrder').serializeObject(),
        resultArray: [
            { orderListProp1: 'value1', orderListProp2: 'value2' },
            { orderListProp1: 'value3', orderListProp2: 'value4' },
            { orderListProp1: 'value5', orderListProp2: 'value6' }
        ]
    }),
    contentType: 'application/json; charset=utf-8'
});


问:
wrong errors required fields in Prestashop 1.6
Since some day I get this errors when I want to edit and save a product in the admin:

This link_rewrite field is required at least in English (English)

Products must be in at least one category.

This product must be in the default category.

But all this field are filled well.

The first error (link_rewrite) I fixed (workaround) by editting \classes\Product.php line 308 changed 'required' => true to 'required' => false. But for error 2 and 3 I didn't find a workaround yet.

Any ideas?

答: How I can remember this version wasn't stable and such issues can appear. If you don't want to update your version to the latest version of core you can look through newer versions of the core, these issues could be fixed in later releases. Also, your solution about first error doesn't seem reliable. You didn't fix a problem, you just have hidden it and this can lead to more dangerous outcomes(especially with a friendly URL)</p>


问:
Build error on Visual Studio 2013 (Windows 7-64bit) while connecting to connector C libraries of MySQL 5.7
Need Help:

I need to connect to MySQL 5.7 using connector/C on visual studio 2013 using a basic C program. I am getting errors linked to my_global.h.

I tried to find the solution on google but I am unsucessful yet.

My Steps:

I downloaded MySQL 5.7 from MySQL webpage, and installed its msi installer sucessfully.

I downloaded its Connector/C from MySQL webpage and installed its msi installer sucessfully. I found out that Connector/C is composed of header files (include files) and a library file (libmysql).

I followed this  tutorial (stackoverflow supported answer)to link library and include files into Visual Studio 2013.

I write the following code on Visual Studio 2013

```<code>#include <my_global.h>
#include <mysql.h>

int main(int argc, char **argv)
{
  MYSQL *conn;
  conn = mysql_init(NULL);

  if (conn == NULL)
  {
      printf("Error %u %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }

  if (mysql_real_connect(conn, "localhost", "root", "asdfasdf", NULL, 0, NULL, 0) == NULL)
  {
      printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }

  if (mysql_query(conn, "CREATE DATABASE testdb"))
  {
      printf("Error %u: %s", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }

  mysql_close(conn);
  return 0;
}
</code>```

It gives error:
Error   2   error C2037: left of 'tv_nsec' specifies undefined struct/union 'timespec'  c:\program files\mysql\mysql connector c 6.1\include\my_global.h    698 1   mysql

Can you help in following matters:

I searched on google and was unable to find any specific tutorial. I searched google, youtube and stackoverflow. The MySQL Reference Manual isn't helping on getting started. Can you suggest me and support me in this problem?

Is there any 1 (just one) ebook or book available on Connecting to MySQL using C programming?

I will be thankful for help!

答:
The linking method is absolutely correct.
I also installed server mysql. I linked the mysql server libraries and it worked fine.</p>

Body:
Need Help:

I need to connect to MySQL 5.7 using connector/C on visual studio 2013 using a basic C program. I am getting errors linked to my_global.h.

I tried to find the solution on google but I am unsucessful yet.

My Steps:

I downloaded MySQL 5.7 from MySQL webpage, and installed its msi installer sucessfully.

I downloaded its Connector/C from MySQL webpage and installed its msi installer sucessfully. I found out that Connector/C is composed of header files (include files) and a library file (libmysql).

I followed this  tutorial (stackoverflow supported answer)to link library and include files into Visual Studio 2013.

I write the following code on Visual Studio 2013

#include <my_global.h>
#include <mysql.h>

int main(int argc, char **argv)
{
  MYSQL *conn;
  conn = mysql_init(NULL);

  if (conn == NULL)
  {
      printf("Error %u %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }

  if (mysql_real_connect(conn, "localhost", "root", "asdfasdf", NULL, 0, NULL, 0) == NULL)
  {
      printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }

  if (mysql_query(conn, "CREATE DATABASE testdb"))
  {
      printf("Error %u: %s", mysql_errno(conn), mysql_error(conn));
      exit(1);
  }

  mysql_close(conn);
  return 0;
}

It gives error:
Error   2   error C2037: left of 'tv_nsec' specifies undefined struct/union 'timespec'  c:\program files\mysql\mysql connector c 6.1\include\my_global.h    698 1   mysql

Can you help in following matters:

I searched on google and was unable to find any specific tutorial. I searched google, youtube and stackoverflow. The MySQL Reference Manual isn't helping on getting started. Can you suggest me and support me in this problem?

Is there any 1 (just one) ebook or book available on Connecting to MySQL using C programming?

I will be thankful for help!


问:
Bootstrap, Popper is missing even after importing bootstrap bundle
I'm struggling with bootstrap4. I've imported the bootstrap.bundle.js which already contain popper.js.

But anyway I get the following error:

```<code>Uncaught ReferenceError: Popper is not defined
</code>```

Including structure

```<code><script type="text/javascript" src=".../js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src=".../js/bootstrap.bundle.min.js"></script>
<script type="text/javascript" src=".../js/bootstrap.min.js"></script>
</code>```

答:
bootstrap.bundle.js or bootstrap.bundle.min.js contains Bootstrap + Popper.js so you just have to include jQuery and Bootstrap Bundle and everything is done

```<code><script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.bundle.min.js" integrity="sha384-3ziFidFTgxJXHMDttyPJKDuTlmxJlwbSkojudK/CkRqKDOmeSbN6KLrGdrBQnT2n" crossorigin="anonymous"></script>
</code>```

Body:
I'm struggling with bootstrap4. I've imported the bootstrap.bundle.js which already contain popper.js.

But anyway I get the following error:

Uncaught ReferenceError: Popper is not defined

Including structure

Body:
bootstrap.bundle.js or bootstrap.bundle.min.js contains Bootstrap + Popper.js so you just have to include jQuery and Bootstrap Bundle and everything is done

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.bundle.min.js" integrity="sha384-3ziFidFTgxJXHMDttyPJKDuTlmxJlwbSkojudK/CkRqKDOmeSbN6KLrGdrBQnT2n" crossorigin="anonymous"></script>


问:
How to add a blurred drop shadow to a button?
I need to add blurred drop shadow to my button:

I tried to create background with layer-list xml drawable, but it not looks like blur.

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Drop Shadow Stack -->
    <item>
        <shape>
            <corners android:radius="45dp" />
            <padding
                android:bottom="2dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />

            <stroke
                android:width="6dp"
                android:color="#007879E8" />

        </shape>
    </item>
    //////   10 more items
        <item>
        <shape>
            <corners android:radius="45dp" />
            <padding
                android:bottom="2dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />

            <stroke
                android:width="6dp"
                android:color="#177879E8" />

        </shape>
    </item>

    <!-- Background -->
    <item>
        <shape>
            <corners android:radius="45dp" />
            <stroke
                android:width="2dp"
                android:color="@color/main_purple_text_color" />
        </shape>
    </item>

</layer-list>
</code>```

Also i tried to use background element behind button with blured png but it uses to many resources and i cannot create selector to change background on hover or click.

I need to have single background file for button and use selector to change blur and gradient on hover/click.
Any ideas how to achieve such effect with Android SDK ?

UPDATE 1

Thanks everybody for answers, but I'm not asking how to create gradient. I've already done this. I need to create blurred drop-shadow.

答:
Create drawable shadow.xml file

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">

<solid android:color="#E3D5FC" />
<corners
    android:radius="20dp"/>
<padding
    android:bottom="1dp"
    android:left="1dp"
    android:right="1dp"
    android:top="1dp" >
</padding>
</code>```

Create another drawable background.xml file

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/shadow" />
<item>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <gradient
            android:angle="0"
            android:centerColor="#9E7CEF"
            android:endColor="#B070EB"
            android:startColor="#8989F4" />
        <corners android:radius="22dp" />
        <size android:height="40dp"/>
    </shape>
</item>
</code>```

and use this file in xml as below.

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
    android:id="@+id/img_save"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/background"
    android:gravity="center"
    android:text="BUTTON"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textColor="@android:color/white"
    android:layout_centerInParent="true"/>
</RelativeLayout>
</code>```

Hope it Helps.

Body:
I need to add blurred drop shadow to my button:

I tried to create background with layer-list xml drawable, but it not looks like blur.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape>
            <corners android:radius="45dp" />
            <padding
                android:bottom="2dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />

            <stroke
                android:width="6dp"
                android:color="#007879E8" />

        </shape>
    </item>
    //////   10 more items
        <item>
        <shape>
            <corners android:radius="45dp" />
            <padding
                android:bottom="2dp"
                android:left="1dp"
                android:right="1dp"
                android:top="1dp" />

            <stroke
                android:width="6dp"
                android:color="#177879E8" />

        </shape>
    </item>

    <item>
        <shape>
            <corners android:radius="45dp" />
            <stroke
                android:width="2dp"
                android:color="@color/main_purple_text_color" />
        </shape>
    </item>

</layer-list>

Also i tried to use background element behind button with blured png but it uses to many resources and i cannot create selector to change background on hover or click.

I need to have single background file for button and use selector to change blur and gradient on hover/click.
Any ideas how to achieve such effect with Android SDK ?

UPDATE 1

Thanks everybody for answers, but I'm not asking how to create gradient. I've already done this. I need to create blurred drop-shadow.

Body:
Create drawable shadow.xml file

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">

<solid android:color="#E3D5FC" />
<corners
    android:radius="20dp"/>
<padding
    android:bottom="1dp"
    android:left="1dp"
    android:right="1dp"
    android:top="1dp" >
</padding>

Create another drawable background.xml file

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/shadow" />
<item>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <gradient
            android:angle="0"
            android:centerColor="#9E7CEF"
            android:endColor="#B070EB"
            android:startColor="#8989F4" />
        <corners android:radius="22dp" />
        <size android:height="40dp"/>
    </shape>
</item>

and use this file in xml as below.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
    android:id="@+id/img_save"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/background"
    android:gravity="center"
    android:text="BUTTON"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textColor="@android:color/white"
    android:layout_centerInParent="true"/>
</RelativeLayout>

Hope it Helps.


问:
Connection hangs infinitely when trying with OpenSSL to RabbitMQ - no error mentioned
I've configured SSL connection in a RabbitMQ server.

When looking into Rabbit logs - I clearly see that Rabbit listens to 5671 port:

```<code>=INFO REPORT==== 5-Dec-2017::15:27:59 ===
started SSL Listener on [::]:5671

=INFO REPORT==== 5-Dec-2017::15:27:59 ===
started SSL Listener on 0.0.0.0:5671
</code>```

Unfortunately, when trying to open connection with OpenSSL:

```<code>openssl s_client -connect myrabbitserver.com:5671 -cert client/cert.pem -key client/key.pem -CAfile testca/cacert.pem
</code>```

I'm getting this response immediately:

```<code>CONNECTED(00000178)
</code>```

And that's it. Client just hangs.
I've tried to set a connection timeout on RabbitMQ server - but it won't help as I don't get any further details regarding any problems.

When I look into RabbitMQ logs - I don't see any request went in.

Any help ?

答:
Things has been working out for me.
I'm using windows so I need to use "\" instead of "\" in rabbit config file.

In addition, it's important to notice policy errors and ignore some of them if you need

Body:
I've configured SSL connection in a RabbitMQ server.

When looking into Rabbit logs - I clearly see that Rabbit listens to 5671 port:

=INFO REPORT==== 5-Dec-2017::15:27:59 ===
started SSL Listener on [::]:5671

=INFO REPORT==== 5-Dec-2017::15:27:59 ===
started SSL Listener on 0.0.0.0:5671

Unfortunately, when trying to open connection with OpenSSL:

openssl s_client -connect myrabbitserver.com:5671 -cert client/cert.pem -key client/key.pem -CAfile testca/cacert.pem

I'm getting this response immediately:

CONNECTED(00000178)

And that's it. Client just hangs.
I've tried to set a connection timeout on RabbitMQ server - but it won't help as I don't get any further details regarding any problems.

When I look into RabbitMQ logs - I don't see any request went in.

Any help ?


问:
MySQL query to get post_id and feature image URL
WordPress considers both a post and the post's featured image as two separate posts, which seems to make it impossible to create a SELECT query putting the post and post's image URL into the same row, like this:

```<code>post_id  imageURL
100      [URL]
</code>```

How do you merge two rows in a MySQL table which have no column with a common value? The value in one column is associated with the value in a different column.

```<code>meta_id   post_id    meta_key          meta_value
100       250        _thumbnail_id     101
101       255       _wp_attached_file  [URL]
</code>```

...to get a result like this

```<code>post_id  imageURL
100      [URL]
</code>```

WordPress seems to have changed it database structure since this question was answered on this site.

I am trying to understand the principle in MySQL of taking the value from one row and showing it in another row, when "Group by" is not available.

Many hours later of watching videos, trial and error, reading answers here, this query gets me only half-way to solving it, but either the Post ID or the Image URL are always missing. I cannot merge two rows to unite the Post with its image URL.

```<code>SELECT * FROM `wp_postmeta`
INNER JOIN wp_posts on wp_posts.id = wp_postmeta.post_id
WHERE wp_postmeta.meta_key = "_wp_attached_file"
ORDER BY `wp_postmeta`.`post_id` DESC
</code>```

Please help. There may be a simple bit of syntax to achieve this, which I am missing. The query is coming in via the WP API, so using raw SQL queries, not the functions available inside WordPress.

答:
The answer came from Raunak Gupta, so thanks to Raunak. Here's the code which solved it.

```<code>SELECT p.id AS post_id, p.post_title, concat('https://www.ourdomain.com','/wp-content/uploads/',pm2.meta_value) AS URL
FROM `wp_posts` AS p
INNER JOIN `wp_postmeta` AS pm1 ON p.id = pm1.post_id
INNER JOIN `wp_postmeta` AS pm2 ON pm1.meta_value = pm2.post_id
AND pm2.meta_key = '_wp_attached_file'
AND pm1.meta_key = '_thumbnail_id'
ORDER BY p.id DESC
</code>```

The key principle needed to create this MySQL query was the self join.

Body:
WordPress considers both a post and the post's featured image as two separate posts, which seems to make it impossible to create a SELECT query putting the post and post's image URL into the same row, like this:

post_id  imageURL
100      [URL]

How do you merge two rows in a MySQL table which have no column with a common value? The value in one column is associated with the value in a different column.

meta_id   post_id    meta_key          meta_value
100       250        _thumbnail_id     101
101       255       _wp_attached_file  [URL]

...to get a result like this

post_id  imageURL
100      [URL]

WordPress seems to have changed it database structure since this question was answered on this site.

I am trying to understand the principle in MySQL of taking the value from one row and showing it in another row, when "Group by" is not available.

Many hours later of watching videos, trial and error, reading answers here, this query gets me only half-way to solving it, but either the Post ID or the Image URL are always missing. I cannot merge two rows to unite the Post with its image URL.

SELECT * FROM `wp_postmeta`
INNER JOIN wp_posts on wp_posts.id = wp_postmeta.post_id
WHERE wp_postmeta.meta_key = "_wp_attached_file"
ORDER BY `wp_postmeta`.`post_id` DESC

Please help. There may be a simple bit of syntax to achieve this, which I am missing. The query is coming in via the WP API, so using raw SQL queries, not the functions available inside WordPress.

Body:
The answer came from Raunak Gupta, so thanks to Raunak. Here's the code which solved it.

SELECT p.id AS post_id, p.post_title, concat('https://www.ourdomain.com','/wp-content/uploads/',pm2.meta_value) AS URL
FROM `wp_posts` AS p
INNER JOIN `wp_postmeta` AS pm1 ON p.id = pm1.post_id
INNER JOIN `wp_postmeta` AS pm2 ON pm1.meta_value = pm2.post_id
AND pm2.meta_key = '_wp_attached_file'
AND pm1.meta_key = '_thumbnail_id'
ORDER BY p.id DESC

The key principle needed to create this MySQL query was the self join.


问:
3D callout line doesn't work with client-side graphics
I am struggling to use callout line with client-side graphics.

I followed the "Point styles for cities" example which uses a feature layer from the "LyonPointsOfInterest (FeatureServer)".

But it doesn't work with a feature layer which creates client-side graphics based on data returned from a web service.

Is there a limitation on 3d callout line?

Here's my code snippet:

Create a feature layer based on layer definition:

```<code>featureLayer = new FeatureLayer({
  fields: this.layerDefinition.fields,
  objectIdField: this.layerDefinition.objectIdField,
  geometryType: this.layerDefinition.geometryType,
  id: this.layerId
});
</code>```

Set elevation and feature reduction and renderer:

```<code>featureLayer.elevationInfo = {
  // elevation mode that will place points on top of the buildings or other SceneLayer 3D objects
  mode: "relative-to-scene"
};
// feature reduction is set to selection because our scene contains too many points and they overlap
featureLayer.featureReduction = {
  type: "selection"
};

featureLayer.renderer = this._getUniqueValueRenderer() as any as Renderer// callout render
</code>```

Here the renderer code:

```<code>_getUniqueValueRenderer() {
  let verticalOffset = { // verticalOffset shifts the symbol vertically
    screenLength: 150, // callout line length
    maxWorldLength: 200,
    minWorldLength: 35
  },
  uniqueValueRenderer = {
    type: "unique-value", // autocasts as new UniqueValueRenderer()
    field: "AQHI",
    uniqueValueInfos: [{
      value: 1,
      symbol: this._get3DCallOutSymbol(verticalOffset, "Museum.png", "#D13470")
    }, {
      value: 2,
      symbol: this._get3DCallOutSymbol(verticalOffset, "Restaurant.png", "#F97C5A")
    }, {
      value: 3,
      symbol: this._get3DCallOutSymbol(verticalOffset, "Church.png", "#884614")
    }, {
      value: 4,
      symbol: this._get3DCallOutSymbol(verticalOffset, "Hotel.png", "#56B2D6")
    }, {
      value: 5,
      symbol: this._get3DCallOutSymbol(verticalOffset, "Park.png", "#40C2B4")
    }, {
      value: 6,
      symbol: this._get3DCallOutSymbol(verticalOffset, "Museum.png", "#D13470")
    }, {
      value: 7,
      symbol: this._get3DCallOutSymbol(verticalOffset, "beer.png", "#F97C5A")
    }, {
      value: 8,
      symbol: this._get3DCallOutSymbol(verticalOffset, "senate.png", "#884614")
    }, {
      value: 9,
      symbol: this._get3DCallOutSymbol(verticalOffset, "Hotel.png", "#56B2D6")
    }, {
      value: 10,
      symbol: this._get3DCallOutSymbol(verticalOffset, "Park.png", "#40C2B4")
    }
  ]};
  return uniqueValueRenderer;
}

_get3DCallOutSymbol(verticalOffset: any, iconName: string, color: string) {
  return {
    type: "point-3d", // autocasts as new PointSymbol3D()
    symbolLayers: [{
      type: "icon", // autocasts as new IconSymbol3DLayer()
      resource: {
        href: this.iconPath + iconName
      },
      size: 20,
      outline: {
        color: "white",
        size: 2
      }
    }],
    verticalOffset: verticalOffset,
    callout: {
      type: "line", // autocasts as new LineCallout3D()
      color: "white",
      size: 2,
      border: {
        color: color
      }
    }
  };
}
</code>```

Set source to an array of graphics, generated based web service data

```<code>featureLayer.source = graphics;
</code>```

答:
You should not use this.layerDefinition in the instanciation a your new FeatureLayer, but put it in a new var. Idem for this.layerId :

```<code>var layerDef = this.layerDefinition;
var lyrId = this.layerId;
featureLayer = new FeatureLayer({
  fields: layerDef.fields,
  objectIdField: layerDef.objectIdField,
  geometryType: layerDef.geometryType,
  id: lyrId
});
</code>```

because this. at this place, is in the scope of new Feature()

Body:
I am struggling to use callout line with client-side graphics.

I followed the "Point styles for cities" example which uses a feature layer from the "LyonPointsOfInterest (FeatureServer)".

But it doesn't work with a feature layer which creates client-side graphics based on data returned from a web service.

Is there a limitation on 3d callout line?

Here's my code snippet:

Create a feature layer based on layer definition:

featureLayer = new FeatureLayer({
  fields: this.layerDefinition.fields,
  objectIdField: this.layerDefinition.objectIdField,
  geometryType: this.layerDefinition.geometryType,
  id: this.layerId
});

Set elevation and feature reduction and renderer:

featureLayer.elevationInfo = {
  // elevation mode that will place points on top of the buildings or other SceneLayer 3D objects
  mode: "relative-to-scene"
};
// feature reduction is set to selection because our scene contains too many points and they overlap
featureLayer.featureReduction = {
  type: "selection"
};

featureLayer.renderer = this._getUniqueValueRenderer() as any as Renderer// callout render

Here the renderer code:

_getUniqueValueRenderer() {
  let verticalOffset = { // verticalOffset shifts the symbol vertically
    screenLength: 150, // callout line length
    maxWorldLength: 200,
    minWorldLength: 35
  },
  uniqueValueRenderer = {
    type: "unique-value", // autocasts as new UniqueValueRenderer()
    field: "AQHI",
    uniqueValueInfos: [{
      value: 1,
      symbol: this._get3DCallOutSymbol(verticalOffset, "Museum.png", "#D13470")
    }, {
      value: 2,
      symbol: this._get3DCallOutSymbol(verticalOffset, "Restaurant.png", "#F97C5A")
    }, {
      value: 3,
      symbol: this._get3DCallOutSymbol(verticalOffset, "Church.png", "#884614")
    }, {
      value: 4,
      symbol: this._get3DCallOutSymbol(verticalOffset, "Hotel.png", "#56B2D6")
    }, {
      value: 5,
      symbol: this._get3DCallOutSymbol(verticalOffset, "Park.png", "#40C2B4")
    }, {
      value: 6,
      symbol: this._get3DCallOutSymbol(verticalOffset, "Museum.png", "#D13470")
    }, {
      value: 7,
      symbol: this._get3DCallOutSymbol(verticalOffset, "beer.png", "#F97C5A")
    }, {
      value: 8,
      symbol: this._get3DCallOutSymbol(verticalOffset, "senate.png", "#884614")
    }, {
      value: 9,
      symbol: this._get3DCallOutSymbol(verticalOffset, "Hotel.png", "#56B2D6")
    }, {
      value: 10,
      symbol: this._get3DCallOutSymbol(verticalOffset, "Park.png", "#40C2B4")
    }
  ]};
  return uniqueValueRenderer;
}

_get3DCallOutSymbol(verticalOffset: any, iconName: string, color: string) {
  return {
    type: "point-3d", // autocasts as new PointSymbol3D()
    symbolLayers: [{
      type: "icon", // autocasts as new IconSymbol3DLayer()
      resource: {
        href: this.iconPath + iconName
      },
      size: 20,
      outline: {
        color: "white",
        size: 2
      }
    }],
    verticalOffset: verticalOffset,
    callout: {
      type: "line", // autocasts as new LineCallout3D()
      color: "white",
      size: 2,
      border: {
        color: color
      }
    }
  };
}

Set source to an array of graphics, generated based web service data

featureLayer.source = graphics;

Body:
You should not use this.layerDefinition in the instanciation a your new FeatureLayer, but put it in a new var. Idem for this.layerId :

var layerDef = this.layerDefinition;
var lyrId = this.layerId;
featureLayer = new FeatureLayer({
  fields: layerDef.fields,
  objectIdField: layerDef.objectIdField,
  geometryType: layerDef.geometryType,
  id: lyrId
});

because this. at this place, is in the scope of new Feature()


问:
How to open ModalDialog on PageLoad
How can I open a modal dialog on PageLoad(), in the constructor of the WebPage and without the AjaxRequestTarget, with Wicket?

答:
I couldn't find a way to open it without an Ajax request, but it's perfectly possible to open it when the page is loaded, with a simple behavior:

HomePage.java

```<code>public class HomePage extends WebPage {
    public HomePage(PageParameters pageParameters) {
        super(pageParameters);

        ModalWindow modal = new ModalWindow("modal");
        modal.add(new OpenWindowOnLoadBehavior());
        modal.setPageCreator(new ModalWindow.PageCreator() {
            @Override
            public Page createPage() {
                return new RedirectPage("http://www.google.com");
            }
        });
        add(modal);
    }
}
</code>```

OpenWindowOnLoadBehavior.java

```<code>public class OpenWindowOnLoadBehavior extends AbstractDefaultAjaxBehavior {
    @Override
    protected void respond(AjaxRequestTarget target) {
        ModalWindow window = (ModalWindow) getComponent();
        window.show(target);
    }
    @Override
    public void renderHead(IHeaderResponse response) {
        response.renderOnLoadJavascript(getCallbackScript().toString());
    }
}
</code>```

HomePage.html

```<code><html xmlns:wicket="http://wicket.apache.org">
<body>
  <div wicket:id="modal"></div>
</body>
</html>
</code>```

Title: How to open ModalDialog on PageLoad

Body:
I couldn't find a way to open it without an Ajax request, but it's perfectly possible to open it when the page is loaded, with a simple behavior:

HomePage.java

public class HomePage extends WebPage {
    public HomePage(PageParameters pageParameters) {
        super(pageParameters);

        ModalWindow modal = new ModalWindow("modal");
        modal.add(new OpenWindowOnLoadBehavior());
        modal.setPageCreator(new ModalWindow.PageCreator() {
            @Override
            public Page createPage() {
                return new RedirectPage("http://www.google.com");
            }
        });
        add(modal);
    }
}

OpenWindowOnLoadBehavior.java

public class OpenWindowOnLoadBehavior extends AbstractDefaultAjaxBehavior {
    @Override
    protected void respond(AjaxRequestTarget target) {
        ModalWindow window = (ModalWindow) getComponent();
        window.show(target);
    }
    @Override
    public void renderHead(IHeaderResponse response) {
        response.renderOnLoadJavascript(getCallbackScript().toString());
    }
}

HomePage.html

<html xmlns:wicket="http://wicket.apache.org">
<body>
  <div wicket:id="modal"></div>
</body>
</html>


问:
How can I view all the git repositories on my machine?
Is there a way in which I can see all the git repositories that exist on my machine? Any command for that?</p>

答:
On Linux and OS X the following command is possibly the fastest (ignoring repositories without .git) when the root directory of find is /:

```<code>find / -name .git -exec dirname {} \; -prune
</code>```

But for roots that have mostly repositories underneath, the following is probably the fastest (you may want to replace / with . or another root):

```<code>find / -type d -exec test -d {}/.git \; -prune -print
</code>```

Quick explanation of the primaries of find used (since no operators are present here, -and is implicit, i.e., for each visited node primaries are evaluated left to right until one of them evaluates to false):

-name is true if the name matches (often, but not here, with wildcards)

-exec executes a command terminated by ; (which is escaped by \ to avoid interpretation by the shell), and is true if the return status is 0 (i.e., OK). The current node is available as {} (which needs no escaping)

-prune is always true, and causes all child nodes to be skipped

-type d is true for directories

-print is needed here because if -exec is present it is not implicitly appended

Body:
On Linux and OS X the following command is possibly the fastest (ignoring repositories without .git) when the root directory of find is /:

find / -name .git -exec dirname {} \; -prune

But for roots that have mostly repositories underneath, the following is probably the fastest (you may want to replace / with . or another root):

find / -type d -exec test -d {}/.git \; -prune -print

Quick explanation of the primaries of find used (since no operators are present here, -and is implicit, i.e., for each visited node primaries are evaluated left to right until one of them evaluates to false):

-name is true if the name matches (often, but not here, with wildcards)

-exec executes a command terminated by ; (which is escaped by \ to avoid interpretation by the shell), and is true if the return status is 0 (i.e., OK). The current node is available as {} (which needs no escaping)

-prune is always true, and causes all child nodes to be skipped

-type d is true for directories

-print is needed here because if -exec is present it is not implicitly appended


问:
Call childs of parent object siblings

Hi, I'm trying to make my own Pokédex site, but sinds I'm not very good at databases, SQL, PHP and such, I'm doing it in JavaScript, JSON style. While doing this I bumped into a problem: I wanted to refer gen1.gps.Route_1.Exits.South to gen1.gps.Pallet_Town.Title but I didn't know how. Of course I searched the internet for a while first, to find a solution, but I didn't understand it in the context.

```<code>var gen1 = {
  'gps': {
    'Route_1': {
      'Title': 'Route 1',
      'Exits': {
        'North': 0,
        'South': // pallet town link here
      },
    },
    'Pallet_Town': {
      'Title': 'Pallet Town',
      'Exits': {
        'North': /* route 1 here */,
        'South': 0
      }
    }
  }
}
</code>```

I expect to be able to call the gen1.gps.Route_1.Exits.South object to get the Title object of gen1.gps.Pallet_Town.

I haven't debugged anything yet so I have no idea what my errors are or will be.

I hope somebody can help me by posting a useful answer.

答:
Need to implement some kind of id system. MySQL takes care of this for you, but like you said, you don't want to have to learn new languages just to see something come to life.

I added IDs to the routes, and then wrote a function to find routes by their IDs. The bottom bit of code (Object.size()) is to get the total number of routes in your gps object. (Same as array.length)

```<code>var gen1 = {
  'gps': {
    'Route_1': {
      'Id': 1,
      'Title': 'Route 1',
      'Exits': {
        'North': 0,
        'South': 2
      },
    },
    'Pallet_Town': {
      'Id': 2,
      'Title': 'Pallet Town',
      'Exits': {
        'North': 1,
        'South': 0
      }
    }
  }
};

function getRoute (id)
{
    for (var i = 0; i < gen1.gps.size(); i++)
    {
        if (gen1.gps[i].id == id)
            return gen1.gps[i];
    }

    return false;
}

Object.size = function (obj)
{
    var size = 0, key;

    for (key in obj)
        if (obj.hasOwnProperty (key)) size++;

    return size;
};
</code>```

Title: Call childs of parent object siblings

Body:
Hi, I'm trying to make my own Pokédex site, but sinds I'm not very good at databases, SQL, PHP and such, I'm doing it in JavaScript, JSON style. While doing this I bumped into a problem: I wanted to refer gen1.gps.Route_1.Exits.South to gen1.gps.Pallet_Town.Title but I didn't know how. Of course I searched the internet for a while first, to find a solution, but I didn't understand it in the context.

var gen1 = {
  'gps': {
    'Route_1': {
      'Title': 'Route 1',
      'Exits': {
        'North': 0,
        'South': // pallet town link here
      },
    },
    'Pallet_Town': {
      'Title': 'Pallet Town',
      'Exits': {
        'North': /* route 1 here */,
        'South': 0
      }
    }
  }
}

I expect to be able to call the gen1.gps.Route_1.Exits.South object to get the Title object of gen1.gps.Pallet_Town.

I haven't debugged anything yet so I have no idea what my errors are or will be.

I hope somebody can help me by posting a useful answer.

Body:
Need to implement some kind of id system. MySQL takes care of this for you, but like you said, you don't want to have to learn new languages just to see something come to life.

I added IDs to the routes, and then wrote a function to find routes by their IDs. The bottom bit of code (Object.size()) is to get the total number of routes in your gps object. (Same as array.length)

var gen1 = {
  'gps': {
    'Route_1': {
      'Id': 1,
      'Title': 'Route 1',
      'Exits': {
        'North': 0,
        'South': 2
      },
    },
    'Pallet_Town': {
      'Id': 2,
      'Title': 'Pallet Town',
      'Exits': {
        'North': 1,
        'South': 0
      }
    }
  }
};

function getRoute (id)
{
    for (var i = 0; i < gen1.gps.size(); i++)
    {
        if (gen1.gps[i].id == id)
            return gen1.gps[i];
    }

    return false;
}

Object.size = function (obj)
{
    var size = 0, key;

    for (key in obj)
        if (obj.hasOwnProperty (key)) size++;

    return size;
};