问:
PHP file not opening with html head tag
When I open this php file, it does not load:

```<code><?php
    echo "I am awesome";
?>
<html>
<head> </head>
</html>
</code>```

Error screenshot

However, if I remove the  tag, code works fine.

I've used both Xampp and Wamp servers on Windows PC, tried changing ports but the issue still persists.

Solved: Using http://127.0.0.1/test.php instead of http://localhost/test.php fixed the problem for me and code executed successfully.

答:
Maybe your Apache server is not working properly, You config again and restart your apache server.
enter image description here</p>

Title: PHP file not opening with html head tag

Body:
When I open this php file, it does not load:

<?php
    echo "I am awesome";
?>

Error screenshot

However, if I remove the  tag, code works fine.

I've used both Xampp and Wamp servers on Windows PC, tried changing ports but the issue still persists.

Solved: Using http://127.0.0.1/test.php instead of http://localhost/test.php fixed the problem for me and code executed successfully.


来源: stackexchange

问:
I want to query EDNS with Bind, what's edns-disabled?
I start Bind in 9.11.2. I want to query some site with EDNS, but I got this problem. How should i do?

```<code>13-Nov-2017 08:05:34.970 dnssec: debug 4: validator @0x7f44897f0f20: dns_validator_destroy
13-Nov-2017 08:05:34.970 edns-disabled: info: success resolving 'www.gds.alibaba.com/A' (in 'gds.alibaba.com'?) after disabling EDNS
13-Nov-2017 08:05:34.970 database: debug 5: dns_adb_destroyfind on find 0x7f4484bd9e20
13-Nov-2017 08:05:34.970 database: debug 5: dns_adb_destroyfind on find 0x7f4484bcae20
13-Nov-2017 08:05:34.970 client: debug 3: client @0x7f44897c7480
</code>```

I turn on the log at level 5(rndc trace 5). I'm confused, how?

```<code>13-Nov-2017 08:05:34.970 edns-disabled: info: success resolving 'www.gds.alibaba.com/A' (in 'gds.alibaba.com'?) after disabling EDNS
</code>```

What's edns-disabled？

答:
The error means that the remote name server that your BIND server tried to talk do doesn't correctly support EDNS (RFC 6891), so BIND failed-over to "plain" DNS instead.

In this particular case, the server is dropping queries that contain the new EDNS Cookie option (RFC 7873) which are sent by default in BIND 9.11.  Dropping the packets in this way is contrary to the EDNS specification.

It is possible to disable sending the EDNS Cookie option by creating a server { } directive in your named.conf file with send-cookie no;

See also https://ednscomp.isc.org/ where there's more information about EDNS (non-)compliance and a compliance testing tool.

The results for gds.alibaba.com are at https://ednscomp.isc.org/ednscomp/004c393a64

ContentLicense: CC BY-SA 3.0

Body:
I start Bind in 9.11.2. I want to query some site with EDNS, but I got this problem. How should i do?

13-Nov-2017 08:05:34.970 dnssec: debug 4: validator @0x7f44897f0f20: dns_validator_destroy
13-Nov-2017 08:05:34.970 edns-disabled: info: success resolving 'www.gds.alibaba.com/A' (in 'gds.alibaba.com'?) after disabling EDNS
13-Nov-2017 08:05:34.970 database: debug 5: dns_adb_destroyfind on find 0x7f4484bd9e20
13-Nov-2017 08:05:34.970 database: debug 5: dns_adb_destroyfind on find 0x7f4484bcae20
13-Nov-2017 08:05:34.970 client: debug 3: client @0x7f44897c7480

I turn on the log at level 5(rndc trace 5). I'm confused, how?

13-Nov-2017 08:05:34.970 edns-disabled: info: success resolving 'www.gds.alibaba.com/A' (in 'gds.alibaba.com'?) after disabling EDNS

What's edns-disabled？


问:
Why can't I connect to 127.0.0.1 HortonWorks Dashboard?
I have installed Virtual Box (Version 5.2.0 r118431 (Qt5.6.2)) on Windows 10 and i imported appliance HDP_2.4_virtualbox_v3 (downloaded from here).

I followed the tutorial from here step by step.

The virtual machine is running on the computer from where I am trying to access the Dashboard. I have set up the Host Only Adapter Option on the sandbox so the computer and the virtual machine can communicate

After the CentOs finished booting I am prompt to enter to the ip 127.0.0.1:8888, which is a different address from the tutorial,

and there is no server listening to that address because i get

"127.0.0.1 refused to connect." in the browser.

image here

答:
Run the ipconfig command in your command prompt and identyfy your virtual box's ip under Ethernet adapter VirtualBox Host-Only Network.

Take that ip address and go to your Virtual Box.

Select your appliance and go to Settings->Network->Adapter 1->Port Forwarding.

Replace the Host IP 127.0.0.1 for the port you need 8080, 8888 and so on with the ip of your virtual box that should be sth like 192.168.x.x.

Now start your sandbox, login on it and try to connect in your browser to the new ip set 192.168.x.x:8888.

Use appliance HDP_2.4_virtualbox because in the most recent some linux commands like netstat are considered deprecated and no longer function, which willmake your life harder when trying to debug or identify a networking problem.

If you still encounter issues eith it, reinstall your operating system, reinstall your virtual box and reimport the sandbox, make the changes needed in the Port Forwarding settings and it should be ok.


问:
What is "stdafx.h" used for in Visual Studio?
A file named stdafx.h is automatically generated when I start a project in Visual Studio 2010. I need to make a cross-platform C++ library, so I don't/can't use this header file.

What is stdafx.h used for? Is it OK that I just remove this header file?

答:
It's a "precompiled header file" -- any headers you include in stdafx.h are pre-processed to save time during subsequent compilations. You can read more about it here on MSDN.

If you're building a cross-platform application, check "Empty project" when creating your project and Visual Studio won't put any files at all in your project.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
flow type for react prop as either of two arrays
```<code>type PropTypes = {
  myProp: Array<{a: string}> | Array<{a: number}>
}
</code>```

If I create a compoennt with PropTypes as seen above I always get the following error:

```<code>myProp: *Array<{a: string}>* | Array<{a: number}>,
<<< object type. This type is incompatible with
myProp: Array<{a: string}> | *Array<{a: number}>*,
</code>```

This seems weird since using Array | Array construct generally works for simple function:

```<code>function foo(x: Array<First> | Array<Second>): string {
  return String(x[0]['a']);
}
No errors!
</code>```

EDIT:
MichaelDeBoey's answer pointed me in the right direction and turns out that the problem occurs when we try to map the prop to anything:

```<code>type PropTypes = {
  myProp: Array<{a: string}> | Array<{a: number}>
}

class TestComponent extends Component<PropTypes> {
  render () {
    this.props.myProp.map(prop => prop)
    return 'whatever'
  }
}
</code>```

答:
Which version of flow are you using?

Tried this with v0.59.0 flow.org/try and it just works.

Maybe you can try with the following (watch on flow.org/try):

type PropTypes = {
  myProp: Array<{a: string} | {a: number}>,
}
```

<p>Or maybe a bit more clear (watch on flow.org/try):</p>

<pre class="lang-js prettyprint-override"><code>type AString = {a: string};
type ANumber = {a: number};
type PropTypes = {
  myProp: Array<AString | ANumber>,
};
</code>```

Body:
type PropTypes = {
  myProp: Array<{a: string}> | Array<{a: number}>
}

If I create a compoennt with PropTypes as seen above I always get the following error:

myProp: *Array<{a: string}>* | Array<{a: number}>,
<<< object type. This type is incompatible with
myProp: Array<{a: string}> | *Array<{a: number}>*,

This seems weird since using Array | Array construct generally works for simple function:

function foo(x: Array<First> | Array<Second>): string {
  return String(x[0]['a']);
}
No errors!

EDIT:
MichaelDeBoey's answer pointed me in the right direction and turns out that the problem occurs when we try to map the prop to anything:

type PropTypes = {
  myProp: Array<{a: string}> | Array<{a: number}>
}

class TestComponent extends Component<PropTypes> {
  render () {
    this.props.myProp.map(prop => prop)
    return 'whatever'
  }
}

Body:
Which version of flow are you using?

Tried this with v0.59.0 flow.org/try and it just works.

Maybe you can try with the following (watch on flow.org/try):

type PropTypes = {
  myProp: Array<{a: string} | {a: number}>,
}

Or maybe a bit more clear (watch on flow.org/try):

type AString = {a: string};
type ANumber = {a: number};
type PropTypes = {
  myProp: Array<AString | ANumber>,
};


问:
Convert list into dict(dictonary). Proc-bridge communication
I'm using https://github.com/gongzhang/proc-bridge lib to communication beetwen python and java code. I need to pass to java code list but I can pass only dict type. Example code looks like:

```<code>host = '127.0.0.1'
port = 8077
list = [1,2,3,4,5,6,7,8,9]

def request_handler(api: str, arg: dict) -> dict:  #-> here that dict
    if api == 'echo':
        return list
    elif api == 'add':
        return {'result': sum(x for x in arg['elements'])}
    else:
        raise Exception('unknown api')

server = ProcBridgeServer(host, port, request_handler)
server.start()
</code>```

There is an option to cast list to looks like that (or maybe change it to pass just list) :

List: [1,2,3,4,5,6,7,8,9]

after cast Dict : [1,2,5,6,7,8,9 : 3,4] ? where 1,2,5,6,7,8,9 are values and 3,4 are both keys

答:
This will convert your list to a dictionary

```<code>alist = [1,2,3,4,5,6,7,8,9]
adict = {}
for value in alist:
    adict[value]=value
</code>```

If the list won't contain a simple range of numbers you could use

```<code>alist = ['oof','hey',3,4,5,6,7,8,9]
adict = {}
for index in range(len(alist)):
    adict[index]=alist[index]
</code>```

Or the simpler version

```<code>alist = ['oof','hey',3,4,5,6,7,8,9]
adict = {'someKey':alist}
</code>```

Body:
I'm using https://github.com/gongzhang/proc-bridge lib to communication beetwen python and java code. I need to pass to java code list but I can pass only dict type. Example code looks like:

host = '127.0.0.1'
port = 8077
list = [1,2,3,4,5,6,7,8,9]

def request_handler(api: str, arg: dict) -> dict:  #-> here that dict
    if api == 'echo':
        return list
    elif api == 'add':
        return {'result': sum(x for x in arg['elements'])}
    else:
        raise Exception('unknown api')

server = ProcBridgeServer(host, port, request_handler)
server.start()

There is an option to cast list to looks like that (or maybe change it to pass just list) :

List: [1,2,3,4,5,6,7,8,9]

after cast Dict : [1,2,5,6,7,8,9 : 3,4] ? where 1,2,5,6,7,8,9 are values and 3,4 are both keys

Body:
This will convert your list to a dictionary

alist = [1,2,3,4,5,6,7,8,9]
adict = {}
for value in alist:
    adict[value]=value

If the list won't contain a simple range of numbers you could use

alist = ['oof','hey',3,4,5,6,7,8,9]
adict = {}
for index in range(len(alist)):
    adict[index]=alist[index]

Or the simpler version

alist = ['oof','hey',3,4,5,6,7,8,9]
adict = {'someKey':alist}


问:
Check uniqueness of ID inside CKEditor content
Task: When adding anchor with id in CKEditor, I want to check id's uniqueness for entire page.

Problem: If I access directly CKEditor content it may have fakeobjects for elements with same id.

If i get CKEditor content with getData() which will return plain html and not DOM.

Question: What is complete and easiest way to check uniqueness of element's id in CKEditor

Thank you!

答:
The fastest way seems to be utilizing CKEditor API and search editor content for:

Regular elements with the same id.

Fake elements holding regular elements with the same id.

Finding regular elements with the same id is easy with CKEDITOR.dom.element.find method:

```<code>var sameIdNode = [],
    regularNodes = editor.editable().find( '[id=' + id + ']' ).toArray();

CKEDITOR.tools.array.forEach( regularNodes, function( node ) {
    // Check if it is not a fake element.
    if ( !node.getAttribute( 'data-cke-realelement' ) ) {
        sameIdNodes.push( node )
    }
} );
</code>```

Similar with fake element, however their real content needs to be decode to be searched:

```<code>var fakeNodes = editor.editable().find( '[data-cke-realelement]' ).toArray(),
    realElement = null,
    sameIdNodes = [];

// Check fake elements.
CKEDITOR.tools.array.forEach( fakeNodes, function( node ) {
    // Decode realelement and convert into CKEDITOR.dom.element so `find` could be used. Wrap in a `div` so find will also check outermost element.
    realElement = CKEDITOR.dom.element.createFromHtml( '<div>' + decodeURIComponent( node.getAttribute( 'data-cke-realelement' ) ) + '</div>' );
    sameIdNodes = sameIdNodes.concat( realElement.find( '[id=' + id + ']' ).toArray() );
} );
</code>```

For the working, simple example check this codepen.

Body:
The fastest way seems to be utilizing CKEditor API and search editor content for:

Regular elements with the same id.

Fake elements holding regular elements with the same id.

Finding regular elements with the same id is easy with CKEDITOR.dom.element.find method:

var sameIdNode = [],
    regularNodes = editor.editable().find( '[id=' + id + ']' ).toArray();

CKEDITOR.tools.array.forEach( regularNodes, function( node ) {
    // Check if it is not a fake element.
    if ( !node.getAttribute( 'data-cke-realelement' ) ) {
        sameIdNodes.push( node )
    }
} );

Similar with fake element, however their real content needs to be decode to be searched:

var fakeNodes = editor.editable().find( '[data-cke-realelement]' ).toArray(),
    realElement = null,
    sameIdNodes = [];

// Check fake elements.
CKEDITOR.tools.array.forEach( fakeNodes, function( node ) {
    // Decode realelement and convert into CKEDITOR.dom.element so `find` could be used. Wrap in a `div` so find will also check outermost element.
    realElement = CKEDITOR.dom.element.createFromHtml( '<div>' + decodeURIComponent( node.getAttribute( 'data-cke-realelement' ) ) + '</div>' );
    sameIdNodes = sameIdNodes.concat( realElement.find( '[id=' + id + ']' ).toArray() );
} );

For the working, simple example check this codepen.


问:
cURL returning XML or JSON
I've got a form say here - http://example.com/palreg.php

Once people register I'll be sending them an email with the link that will allow them to edit their details (I know it's a crazy way of doing things, but I am working on someone else's code so don't mind) for instance the url as such http://example.com/palreg.php?paliD=1234, and when they go to that page the form will be populated with their information so that they can make changes.

Now the problem is that the DB is in a different site and the information has to be passed to that site to perform a select action, to do so I use cURL to send the information like so

```<code>$url = "http://example2.com/processXML.php";
$xmlStr will be like this

<table>tab_name</table>
<action>select</action>
<palid>1234</palid>

$ch=curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, 'xmlstr='.$xmlStr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$data = curl_exec($ch);
</code>```

On the other end (http://example2.com/processXML.php) I convert the xml to an array and perform the query to select pal information based on the id sent.

The real question now is how do I send the retrieved pal information (as xml or json or array) back so that i can populate the form with the returned data.

Also can I do a return $dataArray; in processXML.php and be able to grab it?

OK to make things a bit clearer, what I do in processXML.php is
retrieve the result set and do this

```<code>print json_encode($resultArray);
</code>```

not should I print or return

Thank you, and do let me know if things aren't clear.

答: Just echo out the data you need to send back to the form, in your format of choice, and fetch that response in thepalreg.php.</p>

Title: cURL returning XML or JSON

Body:
I've got a form say here - http://example.com/palreg.php

Once people register I'll be sending them an email with the link that will allow them to edit their details (I know it's a crazy way of doing things, but I am working on someone else's code so don't mind) for instance the url as such http://example.com/palreg.php?paliD=1234, and when they go to that page the form will be populated with their information so that they can make changes.

Now the problem is that the DB is in a different site and the information has to be passed to that site to perform a select action, to do so I use cURL to send the information like so

$url = "http://example2.com/processXML.php";
$xmlStr will be like this

tab_name

<action>select</action>
<palid>1234</palid>

$ch=curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, 'xmlstr='.$xmlStr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$data = curl_exec($ch);

On the other end (http://example2.com/processXML.php) I convert the xml to an array and perform the query to select pal information based on the id sent.

The real question now is how do I send the retrieved pal information (as xml or json or array) back so that i can populate the form with the returned data.

Also can I do a return $dataArray; in processXML.php and be able to grab it?

OK to make things a bit clearer, what I do in processXML.php is
retrieve the result set and do this

print json_encode($resultArray);

not should I print or return

Thank you, and do let me know if things aren't clear.


问:
How to create specific table in MySQL DB using Hibernate
so following situation:

I am using Hibernate to upload/download data to and from the database, which works fine.

Currently I have two tables, "Parent"(which is the parent) and "Child"(which is the child). I have a OneToMany / ManyToOne relationship. I only upload the parent and the child is automatically uploaded due to cascade.
The Parent.class has a List(Child).

If an entity of "Parent" is changed/updated, I want to move the "old version" into a table called "Parent_OLD" (and of course the child via cascade) and add a time stamp to the old entity.

So the problem I am currently encountering is:
I have tried to solve it by creating a new class "Parent_OLD" which looks exactly like the "Parent" except for the time stamp.
So what I did is: Whenever I upload new data to the DB, I check if the entity already exists and if it does I pass the data via "getters" to "Parent_OLD". This works fine so far, because I only have like 3 attributes I need to pass, but if I end up with more fields, it would be handy to have a different solution to this.

But what does not work is to move the "child_OLD" to the "Child_OLD".
So as mentioned above, the Parent.class has a List(Child).
Child_NEW and Child_OLD actually look exactly alike, because they do not need a time stamp. But due to the Hibernate Annotation on top of the Child.class every entity of Child.class is loaded into "Child"-table.

So I created a Child_OLD.class.
This means:
I have a current Parent entity, with a List(Child).
I want to pass the parent (including the list) to the Parent_OLD entity.

But I cannot cast the List(Child) to List(Child_OLD). I have tried casting it to a list of objects and then to Child_OLD, but this did not work.
Passing the attributes via "getters" is no option as the class has like 60 fields.
I also tried creating an abstract class "Child" but I still did not manage to get it to work.

So I thought it would be amazingly simple if I could tell Hibernate to load certain entities into a different table. So maybe something like an annotation above the CheckIfExistsAndIfItDoesCopyToOldTable-Method. Is this possible?
Or does anyone know how I could solve my problem?

I guess I need to apologize because I do not know how clear I managed to explain my problem.
So sorry for the possibly confusing text and thank you in advance for your ideas!

Edit:
I want to backup the Parent as well as the Child.
But this should happen via cascade if possible.
So, by backing up the Parent, the List with the children should be moved into the Child-BackUp-Table.

答:
as i understand you are not planning to save List(Child) to a backup table, this means you don't have to include to field as a DB column.

For the general problem you are having it might be possible to solve it with DB side solution and not a server side one..
have you checked DB triggers ? and DB date columns with default value/ auto generated values ?

MySQL trigger to insert row into another table


问:
What is the most efficient way to do a wordpress conditional ? if_is versus ! if_is_not
What is the most efficient way to do a conditional ?

I'm used to doing conditionals this way -

```<code>if ( is_front_page() ) {

// Do things

else {

return false;

}
</code>```

Is this way more efficient in that in ends early if it's false ?

```<code>if ( ! is_front_page() ) {

return false;

} else

// Do things

{
</code>```

答:
Seems to me that there's no difference in the code examples you've written, at least efficiency wise.
The condition is basically the same. The question is more a semantic question and I believe that this approach is better:

```<code>if ( is_front_page() ) {

// Do things

} else { //YOU FORGOT HERE A CLOSING BRACKET FOR THE IF

return false;

}
</code>```

Furthermore, You can remove the "else" part.
In case the condition returns true then the code will run and finally return true, otherwise - it would return false.

```<code>if ( is_front_page() ) {

  // Do things

  return true;

}
return false;
</code>```

Body:
What is the most efficient way to do a conditional ?

I'm used to doing conditionals this way -

if ( is_front_page() ) {

// Do things

else {

return false;

}

Is this way more efficient in that in ends early if it's false ?

if ( ! is_front_page() ) {

return false;

} else

// Do things

{

Body:
Seems to me that there's no difference in the code examples you've written, at least efficiency wise.
The condition is basically the same. The question is more a semantic question and I believe that this approach is better:

if ( is_front_page() ) {

// Do things

} else { //YOU FORGOT HERE A CLOSING BRACKET FOR THE IF

return false;

}

Furthermore, You can remove the "else" part.
In case the condition returns true then the code will run and finally return true, otherwise - it would return false.

if ( is_front_page() ) {

  // Do things

  return true;

}
return false;


问:
C# CNTK Sparse (and others) using MinibatchSource
I just started using CNTK C# API and, so far, I have had no problem loading files if I write them in a way that I can read using full matrix readers, e.g., the MNIST tutorial example:

MinibatchSource minibatchSourceExistModel = MinibatchSource.TextFormatMinibatchSource(
                    Path.Combine(ImageDataFolder, "MNIST_test.ctk"), streamConfigurations);

I am confused with sparse data though. It would help to have a C# reference with examples of all possible forms of input to load using the MinibatchSource.

Do I need to save all the zeroes in the file? Is there an example file showing how to write sparse data and load it to use as MinibatchSource input?

Thanks

答:
I create my .CTF with sparse data like below. It is data with 4 different classes and has a sparse features array where all features included are set to 1

|c 0 0 0 1 |f  3:1  11:1  20:1  23:1  25:1  94:1

|c 0 0 1 0 |f  3:1  5:1  16:1  23:1  25:1 189:1  190:1

The CTF file format is more flexible but this works and I can feed it using the C# API as a minibatchsource.

There are good examples in this document (skip the first part)
https://learn.microsoft.com/en-us/cognitive-toolkit/brainscript-cntktextformat-reader


问:
Yii2 - rest - encrypt output for all actions
I'm writing an Yii restfull application. I could manage the input by overwrite ActiveController and init() method. But I want to encrypt the output of all actions of all controllers and unfortunately I have no idea how can I do that...!

Can any one help me ...?

答:
You could use action events to modify data before or after executing controllers. Just override EVENT_AFTER_ACTION event, get the output generated and encrypt it with whatever algorithm you desire.

Then the output of all actions in the controller with be encrypted.

Here is a good reference for Yii2 events:

Yii2 events documentation

Yii2 events API guide


问:
Process Manager
I'm trying to make a kernel simulation as my DSA (data structure and algorithm) project in C++. There will be different modules(process manager, memory manager etc.) in it. Right now i have to make a Process Manager and I've only a little a idea about it (like, i can use a queue). Can anyone help me how can i make a process manager in c++. </p>

答:
A process manager manages processes. Obviously, to refine that, you first need to define what constitutes a process in your OS. There's no reason for a process manager to deal with threads when all your processes are single-threaded, for instance. And if you don't have virtual memory, that doesn't need to be managed either.

You did note that you'd have a memory manager. This is certainly possible outside the process manager, but you would need to define the interface between them. For instance, the process manager would need to allocate memory to load the program code on startup; the program itself cannot do that (chicken and egg problem).

Title: Process Manager


问:
Is it considered better practice in Python to pass tuples instead of lists to functions?
In Python is it better practice to write functions that accept tuples instead of lists if the data passed should be unmodified? Similar to how passing arguments by const reference in C++ makes it clear to the user that data won't be modified.

答: No, tuples and lists are different things. Tuples have strucure, lists have order. Use each for its own purpose.</p>


问:
Magento 2 - How to get cart items total in header.phtml
I am working with magento 2. I got php error when am using

```<code>echo Mage::helper(‘checkout/cart’)->getCart()->getItemsCount();
</code>```

how to get cart item count in magento 2?

答:
Magento 2 provides 2 ways to show items count. One shows the number of individual items in the cart, while the other one shows the total count of items in the cart.

Let us say that cart helper is;

$helper = $this->helper('\Magento\Checkout\Helper\Cart');

When you do:

echo $counter->getItemsCount();

it will show the number of individual items in the cart.

If you want to show total items count, then use:

echo $counter->getSummaryCount();

Body:
I am working with magento 2. I got php error when am using

echo Mage::helper(‘checkout/cart’)->getCart()->getItemsCount();

how to get cart item count in magento 2?


问:
Clear an interval when the last element is update
I'm trying to stop an interval when my last element is update.

I do not know how to do. Can you get me started on tracks?

At the moment I clear my interval when I leave the page.

```<code>    this.subscriptions.push(this.requestId.subscribe(id => {
        this.store.dispatch(new requestActions.LoadRequest(id));
        this.interval = setInterval(() => {
            this.store.dispatch(new requestActions.LoadRequest(id));
        }, 1700);
    }));
</code>```

My effect :

```<code>@Effect()
loadRequest$: Observable<Action> = this.actions$
    .ofType<requestActions.LoadRequest>(requestActions.LOAD_REQUEST)
    .switchMap(action => {
        return this.apiService
            .loadRequest(action.payload)
            .map((task: RequestTask[]) => new requestActions.LoadRequestSuccessAction(task))
            .catch(error => of(new requestActions.LoadRequestFailureAction(error)));
    });
</code>```

my reducer :

```<code>    case request.LOAD_REQUEST_SUCCESS:
        console.log("Payload : ", action.payload);
        return {
            ...adapter.addAll(action.payload, state),
            loaded: true,
            selectedIndex: null
        } as State;
</code>```

答:
add error and complete state.

```<code>this.subscriptions.push(this.requestId.subscribe(id => {
    this.store.dispatch(new requestActions.LoadRequest(id));
    this.interval = setInterval(() => {
        this.store.dispatch(new requestActions.LoadRequest(id));
    }, 1700);
}),(err)=>{console.log(err);},
()=>{
    clearInterval(this.interval);
}
);
</code>```

Body:
I'm trying to stop an interval when my last element is update.

I do not know how to do. Can you get me started on tracks?

At the moment I clear my interval when I leave the page.

    this.subscriptions.push(this.requestId.subscribe(id => {
        this.store.dispatch(new requestActions.LoadRequest(id));
        this.interval = setInterval(() => {
            this.store.dispatch(new requestActions.LoadRequest(id));
        }, 1700);
    }));

My effect :

@Effect()
loadRequest$: Observable<Action> = this.actions$
    .ofType<requestActions.LoadRequest>(requestActions.LOAD_REQUEST)
    .switchMap(action => {
        return this.apiService
            .loadRequest(action.payload)
            .map((task: RequestTask[]) => new requestActions.LoadRequestSuccessAction(task))
            .catch(error => of(new requestActions.LoadRequestFailureAction(error)));
    });

my reducer :

    case request.LOAD_REQUEST_SUCCESS:
        console.log("Payload : ", action.payload);
        return {
            ...adapter.addAll(action.payload, state),
            loaded: true,
            selectedIndex: null
        } as State;

Body:
add error and complete state.

this.subscriptions.push(this.requestId.subscribe(id => {
    this.store.dispatch(new requestActions.LoadRequest(id));
    this.interval = setInterval(() => {
        this.store.dispatch(new requestActions.LoadRequest(id));
    }, 1700);
}),(err)=>{console.log(err);},
()=>{
    clearInterval(this.interval);
}
);


问:
how to prevent currency from going back to default currency in shopify checkout?
I have 2 currencies available in my shopify site. AED and USD. AED is the default currency. So if I choose USD in my site it converts all the product prices to USD perfectly, even until the cart. But when I click check out, it converts back to the default currency of AED.

Can anyone please help me out on this? I want to fix the chosen currency until the checkout site for my customers.

答:
Yes this is very unfortunate but Truth that Shopify Convert all currencies to store base(default) currency at checkout page.

Why This Happens: Because in Shopify Normal plan your checkout page url is something like http://checkout.shopify.com/xxxxxx that specifies that your customer are using shopify checkout url.

Solutions :

Switch to Shopify Plus Plan (Very Costly for small business)

Implement some banner showing conversion rate and message on checkout and cart pages.

Or Wait for something new to come with this feature that shopify promised years back.


问:
Custom image link in WooCommerce product category archive pages
Is there an easy way to set Woocommerce 3.x to link to full size image instead of the product details on the category pages (where you see the thumbs of products)?

So basically it will work as a gallery of some sort with an 'add to cart' buttons below each image.

I assume I have to edit the woocommerce_template_loop_product_link_open() function at includes\wc-template-functions.php and change:

```<code>esc_url( get_the_permalink() )
</code>```

To something else…

答:
Important note:  Never override any core file as you can use available hooks
  (or also you can override WooCommerce templates via a Theme)…

To set Woocommerce 3.x to link to full size image on the category archive pages only, use this:

```<code>add_action ('woocommerce_before_shop_loop_item', 'custom_loop_product_link_open', 1);
function custom_loop_product_link_open(){
    // For product category archives pages only
    if(is_product_category()){
        // Remove default image link
        remove_action ('woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10);
        // Add custom image link function
        add_action ('woocommerce_before_shop_loop_item', 'change_loop_product_link_open', 10);
    }
}

// Custom image link function
function change_loop_product_link_open(){
    global $product; // Get the WC_Product object

    echo '<a href="' . get_the_post_thumbnail_url( $product->get_id(), 'full' )  . '" class="woocommerce-LoopProduct-link">';
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works…

Body:
Is there an easy way to set Woocommerce 3.x to link to full size image instead of the product details on the category pages (where you see the thumbs of products)?

So basically it will work as a gallery of some sort with an 'add to cart' buttons below each image.

I assume I have to edit the woocommerce_template_loop_product_link_open() function at includes\wc-template-functions.php and change:

esc_url( get_the_permalink() )

To something else…

Body:
Important note:  Never override any core file as you can use available hooks
  (or also you can override WooCommerce templates via a Theme)…

To set Woocommerce 3.x to link to full size image on the category archive pages only, use this:

add_action ('woocommerce_before_shop_loop_item', 'custom_loop_product_link_open', 1);
function custom_loop_product_link_open(){
    // For product category archives pages only
    if(is_product_category()){
        // Remove default image link
        remove_action ('woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10);
        // Add custom image link function
        add_action ('woocommerce_before_shop_loop_item', 'change_loop_product_link_open', 10);
    }
}

// Custom image link function
function change_loop_product_link_open(){
    global $product; // Get the WC_Product object

    echo '<a href="' . get_the_post_thumbnail_url( $product->get_id(), 'full' )  . '" class="woocommerce-LoopProduct-link">';
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works…


问:
How can Snakemake be made to update files in a hierarchical rule-based manner when a new file appears at the bottom of the hierarchy?
I have a snakefile with dozens of rules, and it processes thousands of files.  This is a bioinformatics pipeline for DNA sequencing analysis.  Today I added two more samples to my set of samples, and I expected to be able to run snakemake and it would automatically determine which rules to run on which files to process the new sample files and all files that depend on them on up the hierarchy to the very top level.  However, it does nothing.  And the -R option doesn't do it either.

The problem is illustrated with this snakefile:

```<code>> cat tst
rule A:
    output: "test1.txt"
    input: "test2.txt"
    shell: "cp {input} {output}"

rule B:
    output: "test2.txt"
    input: "test3.txt"
    shell: "cp {input} {output}"

rule C:
    output: "test3.txt"
    input: "test4.txt"
    shell: "cp {input} {output}"

rule D:
    output: "test4.txt"
    input: "test5.txt"
    shell: "cp {input} {output}"
</code>```

Execute it as follows:

```<code>> rm test*.txt
> touch test2.txt
> touch test1.txt
> snakemake -s tst -F
</code>```

Output is:

```<code>Provided cores: 1
Rules claiming more threads will be scaled down.
Job counts:
    count   jobs
    1   A
    1

rule A:
    input: test2.txt
    output: test1.txt
    jobid: 0

Finished job 0.
1 of 1 steps (100%) done
</code>```

Since test5.txt does not exist, I expected an error message to that effect, but it did not happen. And of course, test3.txt and test4.txt do not exist.

Furthermore, using -R instead of -F results in "Nothing to be done."
Using "-R A" runs rule A only.

This relates to my project in that it shows that Snakemake does not analyze the entire dependent tree if you tell it to build a rule at the top of the tree and that rule's output and input files already exist.  And the -R option does not force it either.  When I tried -F on my project, it started rebuilding the entire thing, including files that did not need to be rebuilt.

It seems to me that this is fundamental to what Snakemake should be doing, and I just don't understand it.  The only way I can see to get my pipeline to analyze the new samples is to individually invoke each rule required for the new files, in order.  And that is way too tedious and is one reason why I used Snakemake in the first place.

Help!

答:
Snakemake does not automatically trigger re-runs when adding new input files (e.g. samples) to the DAG. However, you can enforce this as outlined in the FAQ.

The reason for not doing this by default is mostly consistency: in order to do this, Snakemake needs to store meta information. Hence, if the meta information is lost, you would have a different behavior than if it was there.
However, I might change this in the future. With such fundamental changes though, I am usually very careful in order to not forget a counter example where the current default behavior is of advantage.

Body:
I have a snakefile with dozens of rules, and it processes thousands of files.  This is a bioinformatics pipeline for DNA sequencing analysis.  Today I added two more samples to my set of samples, and I expected to be able to run snakemake and it would automatically determine which rules to run on which files to process the new sample files and all files that depend on them on up the hierarchy to the very top level.  However, it does nothing.  And the -R option doesn't do it either.

The problem is illustrated with this snakefile:

> cat tst
rule A:
    output: "test1.txt"
    input: "test2.txt"
    shell: "cp {input} {output}"

rule B:
    output: "test2.txt"
    input: "test3.txt"
    shell: "cp {input} {output}"

rule C:
    output: "test3.txt"
    input: "test4.txt"
    shell: "cp {input} {output}"

rule D:
    output: "test4.txt"
    input: "test5.txt"
    shell: "cp {input} {output}"

Execute it as follows:

> rm test*.txt
> touch test2.txt
> touch test1.txt
> snakemake -s tst -F

Output is:

Provided cores: 1
Rules claiming more threads will be scaled down.
Job counts:
    count   jobs
    1   A
    1

rule A:
    input: test2.txt
    output: test1.txt
    jobid: 0

Finished job 0.
1 of 1 steps (100%) done

Since test5.txt does not exist, I expected an error message to that effect, but it did not happen. And of course, test3.txt and test4.txt do not exist.

Furthermore, using -R instead of -F results in "Nothing to be done."
Using "-R A" runs rule A only.

This relates to my project in that it shows that Snakemake does not analyze the entire dependent tree if you tell it to build a rule at the top of the tree and that rule's output and input files already exist.  And the -R option does not force it either.  When I tried -F on my project, it started rebuilding the entire thing, including files that did not need to be rebuilt.

It seems to me that this is fundamental to what Snakemake should be doing, and I just don't understand it.  The only way I can see to get my pipeline to analyze the new samples is to individually invoke each rule required for the new files, in order.  And that is way too tedious and is one reason why I used Snakemake in the first place.

Help!


问:
onPlaybackNearlyFinished does not work
I have the following problem with Java on AWS lambda:

The Intent called "PlaybackNearlyFinished" does not work, aka, does not play the audio file I am feeding it. Can anybody crack exactly why this doesn't work?

Here is my Java Code:

```<code>@Override
  public SpeechletResponse onPlaybackFinished(SpeechletRequestEnvelope<PlaybackFinishedRequest>
                                                      speechletRequestEnvelope) {
    // logging info("onPlaybackFinished start");

    SpeechletResponse response = new SpeechletResponse();

    Stream stream = new Stream();
    stream.setToken("test mp3");
    stream.setUrl("https://ia802508.us.archive.org/5/items/testmp3testfile/mpthreetest.mp3");
    stream.setOffsetInMilliseconds(0);

    AudioItem audioItem = new AudioItem();
    audioItem.setStream(stream);

    PlayDirective playDirective = new PlayDirective();
    playDirective.setAudioItem(audioItem);
    playDirective.setPlayBehavior(PlayBehavior.REPLACE_ALL);

    List<Directive> directives = new ArrayList<>();
    directives.add(playDirective);
    response.setDirectives(directives);
    response.setShouldEndSession(true);
    // logging info("onPlaybackFinished end, return testmp3");

    return response;
  }
</code>```

答:
a couple of points here:

The method you showed had the name of onPlaybackFinished while it should have been onPlaybackNearlyFinished

Looks like the new stream misses the expected previous token. It should be equal to the token of the stream that is finishing - requestEnvelope.getRequest().getToken()

I would also made it PlayBehavior.ENQUEUE instead of PlayBehavior.REPLACE_ALL but I am not sure here... still experimenting

Hope it helps!

Title: onPlaybackNearlyFinished does not work

Body:
I have the following problem with Java on AWS lambda:

The Intent called "PlaybackNearlyFinished" does not work, aka, does not play the audio file I am feeding it. Can anybody crack exactly why this doesn't work?

Here is my Java Code:

@Override
  public SpeechletResponse onPlaybackFinished(SpeechletRequestEnvelope<PlaybackFinishedRequest>
                                                      speechletRequestEnvelope) {
    // logging info("onPlaybackFinished start");

    SpeechletResponse response = new SpeechletResponse();

    Stream stream = new Stream();
    stream.setToken("test mp3");
    stream.setUrl("https://ia802508.us.archive.org/5/items/testmp3testfile/mpthreetest.mp3");
    stream.setOffsetInMilliseconds(0);

    AudioItem audioItem = new AudioItem();
    audioItem.setStream(stream);

    PlayDirective playDirective = new PlayDirective();
    playDirective.setAudioItem(audioItem);
    playDirective.setPlayBehavior(PlayBehavior.REPLACE_ALL);

    List<Directive> directives = new ArrayList<>();
    directives.add(playDirective);
    response.setDirectives(directives);
    response.setShouldEndSession(true);
    // logging info("onPlaybackFinished end, return testmp3");

    return response;
  }


问:
styling for all elements except for a div and all divs inside it

$('#main div').not('#2 > #3').each(function() {
  $(this).css('background-color', 'blue');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">

  <div id="1">
    <div>Some text in paragraph 1</div>
    <div>Some text in paragraph 1</div>
  </div><br>
  <div id="2">
    <div id="3">Some text in paragraph 2</div>
    <div>Some text in paragraph 1</div>
  </div><br>
  <div id="3">
    <div>Some text in paragraph 3</div>
    <div>Some text in paragraph 1</div>
  </div><br>

</div></code>```

I want the css not to be applied for the nested divs of div with id=2. Any suggestions?

答:
A) if your mean be #3 only:

default value for background-color is transparent. you do not set background-color for #3 for this reason it get transparent(in this case, you see blue color,because #2 have background-color:blue).

your selector is correct just insert initial value for divs:

```<code>div {
  background-color:#fff;
}
</code>```

Demo

B) If your mean be #2 and his childrens:

Do not start the ID with the number(I change #2 to #a2)

Use this:

```<code>#main>div:not(#a2) {
    background-color: blue!important;
}
</code>```

#main>div:not(#a2) {
  background-color: blue!important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="main">
  <div id="1">
    <div>Some text in paragraph 1</div>
    <div>Some text in paragraph 1</div>
  </div><br>
  <div id="a2">
    <div id="3">Some text in paragraph 2</div>
    <div>Some text in paragraph 1</div>
  </div><br>
  <div id="3">
    <div>Some text in paragraph 3</div>
    <div>Some text in paragraph 1</div>
  </div><br>
</div></code>```

Body:
$('#main div').not('#2 > #3').each(function() {
  $(this).css('background-color', 'blue');
});

Some text in paragraph 1

Some text in paragraph 1

Some text in paragraph 2

Some text in paragraph 1

Some text in paragraph 3

Some text in paragraph 1

I want the css not to be applied for the nested divs of div with id=2. Any suggestions?

Body:
A) if your mean be #3 only:

default value for background-color is transparent. you do not set background-color for #3 for this reason it get transparent(in this case, you see blue color,because #2 have background-color:blue).

your selector is correct just insert initial value for divs:

div {
  background-color:#fff;
}

Demo

B) If your mean be #2 and his childrens:

Do not start the ID with the number(I change #2 to #a2)

Use this:

#main>div:not(#a2) {
    background-color: blue!important;
}

#main>div:not(#a2) {
  background-color: blue!important;
}

<div id="main">
  <div id="1">
    <div>Some text in paragraph 1</div>
    <div>Some text in paragraph 1</div>
  </div><br>
  <div id="a2">
    <div id="3">Some text in paragraph 2</div>
    <div>Some text in paragraph 1</div>
  </div><br>
  <div id="3">
    <div>Some text in paragraph 3</div>
    <div>Some text in paragraph 1</div>
  </div><br>
</div>


问:
Confusion using object oriented design .. need help
Let say we have an Order class and OrderManagerService class.

Order class: [some state and methods that act on the state]

Item[]

status

OrderManagerService class: [have no state. only following static methods]

createOrder

getOrder

Question: Let say we are using a relational DB in the back. Our goal is to update Order status. Well, the status need to get updated in the DB. My concern is where to put the updateStatus method.

Should I call OrderManagerService.getOrder then, call Order.updateStatus?

or create a new method as OrderManagerService.updateOrderStatus?

well, 1st option seems following encapsulation. But, personally I dont like it as we may end up calling DAO layer from entity objects [perhaps, that might be ok]. Wondering what would be a right design choice and why? any help is greatly appreciated.

答:
Why is there a separate OrderManagerService class? I'd bung all those methods into Order.

(That's probably not theoretically correct or gang-of-four-compliant design pattern but I dn't care because it would make more sense.)


问:
Show elements of array in button text in Objective-C
I'm saving the textfields data in SQLite when click the save button. Now I want to show that data in button text. I'm getting data from SQLite in an NSMutableArray,  but when I set the titleLabel of button it does not appear there. How can I get the array data in button text. My code to get data from SQLite is this:

```<code>- (IBAction)btnShow:(id)sender {

    NSString *show=[[NSString alloc]initWithFormat:@"select * from persondata where id='%@'",_txtID.text];

    dboperation *db = [[dboperation alloc]init];
    _arrmainData = [[NSMutableArray alloc]init];
    _arrmainData=[db getalluser:show];

    NSLog(@"Arr %@",_arrmainData);

    for (NSDictionary * oneCustomer in _arrmainData){
        [oneCustomer objectForKey:@"address"];
        NSLog(@"ID: %@ ",oneCustomer);
        _btnShowData.titleLabel.text = [NSString stringWithFormat:@"%@",oneCustomer];
        NSLog(@"XX %@",_btnShowData.titleLabel.text);
    }
}
</code>```

答:
Set the title like this</p>

```<code>  [_btnShowData setTitle: [NSString stringWithFormat:@"%@", [oneCustomer objectForKey:@"address"]] forState:UIControlStateNormal];
</code>```

Body:
I'm saving the textfields data in SQLite when click the save button. Now I want to show that data in button text. I'm getting data from SQLite in an NSMutableArray,  but when I set the titleLabel of button it does not appear there. How can I get the array data in button text. My code to get data from SQLite is this:

- (IBAction)btnShow:(id)sender {

    NSString *show=[[NSString alloc]initWithFormat:@"select * from persondata where id='%@'",_txtID.text];

    dboperation *db = [[dboperation alloc]init];
    _arrmainData = [[NSMutableArray alloc]init];
    _arrmainData=[db getalluser:show];

    NSLog(@"Arr %@",_arrmainData);

    for (NSDictionary * oneCustomer in _arrmainData){
        [oneCustomer objectForKey:@"address"];
        NSLog(@"ID: %@ ",oneCustomer);
        _btnShowData.titleLabel.text = [NSString stringWithFormat:@"%@",oneCustomer];
        NSLog(@"XX %@",_btnShowData.titleLabel.text);
    }
}

Body:
Set the title like this

  [_btnShowData setTitle: [NSString stringWithFormat:@"%@", [oneCustomer objectForKey:@"address"]] forState:UIControlStateNormal];


问:
How to split string in multiple columns in SQL Server 2012?
I have a table in with a column that has values like this:

```<code>["L", "L", "L", "D", "L", "D", "L", "L", "L", "D"] ,
</code>```

I have to add it in another table which will be 10 columns and response will be 1 for character "L" , 0 for character "D".

My column names will be dynamic as the string contains 240 items of L and D. In the above example, only 10 are present. Column name will be item1, item2 and so on.

答:
What about XML node method have you tried ever

```<code>select distinct
      case (a.value ('/A[1]', 'VARCHAR(MAX)')) when '"L"' THEN 1 WHEN ' "D"' THEN 0 END  [Column1],
      case (a.value ('/A[2]', 'VARCHAR(MAX)')) when ' "L"' THEN 1 WHEN ' "D"' THEN 0 END  [Column2],
      case (a.value ('/A[3]', 'VARCHAR(MAX)')) when ' "L"' THEN 1 WHEN ' "D"' THEN 0 END  [Column3],
      case (a.value ('/A[4]', 'VARCHAR(MAX)')) when ' "L"' THEN 1 WHEN ' "D"' THEN 0 END  [Column4],
      case (a.value ('/A[5]', 'VARCHAR(MAX)')) when ' "L"' THEN 1 WHEN ' "D"' THEN 0 END  [Column5],
      case (a.value ('/A[6]', 'VARCHAR(MAX)')) when ' "L"' THEN 1 WHEN ' "D"' THEN 0 END  [Column6],
      case (a.value ('/A[7]', 'VARCHAR(MAX)')) when ' "L"' THEN 1 WHEN ' "D"' THEN 0 END  [Column7],
      case (a.value ('/A[8]', 'VARCHAR(MAX)')) when ' "L"' THEN 1 WHEN ' "D"' THEN 0 END  [Column8],
      case (a.value ('/A[9]', 'VARCHAR(MAX)')) when ' "L"' THEN 1 WHEN ' "D"' THEN 0 END  [Column9],
      case (a.value ('/A[10]', 'VARCHAR(MAX)')) when ' "L"' THEN 1 WHEN ' "D"' THEN 0 END  [Column10]

      from
(
    SELECT CAST('<A>'+REPLACE(REPLACE(REPLACE(@DATA, '[', ''), ']', ''), ',', '</A><A>')+'</A>' AS XML) AS Data
    --FROM <table_name>
) A CROSS APPLY Data.nodes ('/A') as split(a)
</code>```

Result :

```<code>Column1 Column2 Column3 Column4 Column5 Column6 Column7 Column8 Column9 Column10
    1       1       1       0       1       0       1        1      1       0
</code>```

Body:
I have a table in with a column that has values like this:

["L", "L", "L", "D", "L", "D", "L", "L", "L", "D"] ,

I have to add it in another table which will be 10 columns and response will be 1 for character "L" , 0 for character "D".

My column names will be dynamic as the string contains 240 items of L and D. In the above example, only 10 are present. Column name will be item1, item2 and so on.

Body:
What about XML node method have you tried ever

select distinct
      case (a.value ('/A[1]', 'VARCHAR(MAX)')) when '"L"' THEN 1 WHEN ' "D"' THEN 0 END  [Column1],
      case (a.value ('/A[2]', 'VARCHAR(MAX)')) when ' "L"' THEN 1 WHEN ' "D"' THEN 0 END  [Column2],
      case (a.value ('/A[3]', 'VARCHAR(MAX)')) when ' "L"' THEN 1 WHEN ' "D"' THEN 0 END  [Column3],
      case (a.value ('/A[4]', 'VARCHAR(MAX)')) when ' "L"' THEN 1 WHEN ' "D"' THEN 0 END  [Column4],
      case (a.value ('/A[5]', 'VARCHAR(MAX)')) when ' "L"' THEN 1 WHEN ' "D"' THEN 0 END  [Column5],
      case (a.value ('/A[6]', 'VARCHAR(MAX)')) when ' "L"' THEN 1 WHEN ' "D"' THEN 0 END  [Column6],
      case (a.value ('/A[7]', 'VARCHAR(MAX)')) when ' "L"' THEN 1 WHEN ' "D"' THEN 0 END  [Column7],
      case (a.value ('/A[8]', 'VARCHAR(MAX)')) when ' "L"' THEN 1 WHEN ' "D"' THEN 0 END  [Column8],
      case (a.value ('/A[9]', 'VARCHAR(MAX)')) when ' "L"' THEN 1 WHEN ' "D"' THEN 0 END  [Column9],
      case (a.value ('/A[10]', 'VARCHAR(MAX)')) when ' "L"' THEN 1 WHEN ' "D"' THEN 0 END  [Column10]

      from
(
    SELECT CAST('<A>'+REPLACE(REPLACE(REPLACE(@DATA, '[', ''), ']', ''), ',', '</A><A>')+'</A>' AS XML) AS Data
    --FROM <table_name>
) A CROSS APPLY Data.nodes ('/A') as split(a)

Result :

Column1 Column2 Column3 Column4 Column5 Column6 Column7 Column8 Column9 Column10
    1       1       1       0       1       0       1        1      1       0


问:
Update ListView row on click of Floating Action Button
I currently have a Floating Action Buttons that will record some speech when held down. Once the Button is released I would like a particular row on a ListView to show a play Button.

I have the index of the row in a variable named "selected". But I do not know how to make the ImageButton on that row visible from within the FAB.OnClickListener. Any suggestions?

Thanks

答:
If you want only one item of your list view to show the play button put a variable int playButtonPosition = -1 in your adapter.

In getView method of your adapter, check if (position == playButtonPosition) and show your button here.

In FAB.OnClickListener update adapter.playButtonPosition = selected and notify your adapter about the changes adapter.notifyDataSetChanged().


问:
How to Use Navigation Push Asycn in Master Detail Page
I want to make my xamarin forms app when the menu item is clicked instead change the master detail page it go to another page and shows navigation bar with back button in the top. but i got confused in how to change the on menu item selected, here is my onmenuitemSelected

```<code>private void OnMenuItemSelected(object sender, SelectedItemChangedEventArgs e)
{

        var item = (DrawerItem)e.SelectedItem;
        Type page = item.TargetType;

        //Navigation.PushAsync((Page)Activator.CreateInstance(page));
        //new NavigationPage((Page)Activator.CreateInstance(page));

        Detail = new NavigationPage((Page)Activator.CreateInstance(page));
       IsPresented = false;
    }
</code>```

As you can see in the comment tag i already try to do Navigation.Push async and tried New NavigationPage only without Detail but when im click the menu item its do nothing, so what code should i write to do that. and so here what i try to do
and this is what i get when i click the item in the masterdetail page

what code should i write to able do that ?

答:
nevermind i already found the solution to my problem, here if you have same problem like me</p>

```<code>private void OnMenuItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var item = (MasterPageItem)e.SelectedItem;
Type page = item.TargetType;
// Detail = new NavigationPage((Page)Activator.CreateInstance(page));
Detail.Navigation.PushAsync((Page)Activator.CreateInstance(page));
IsPresented = false;
}
</code>```

Body:
I want to make my xamarin forms app when the menu item is clicked instead change the master detail page it go to another page and shows navigation bar with back button in the top. but i got confused in how to change the on menu item selected, here is my onmenuitemSelected

private void OnMenuItemSelected(object sender, SelectedItemChangedEventArgs e)
{

        var item = (DrawerItem)e.SelectedItem;
        Type page = item.TargetType;

        //Navigation.PushAsync((Page)Activator.CreateInstance(page));
        //new NavigationPage((Page)Activator.CreateInstance(page));

        Detail = new NavigationPage((Page)Activator.CreateInstance(page));
       IsPresented = false;
    }

As you can see in the comment tag i already try to do Navigation.Push async and tried New NavigationPage only without Detail but when im click the menu item its do nothing, so what code should i write to do that. and so here what i try to do
and this is what i get when i click the item in the masterdetail page

what code should i write to able do that ?

Body:
nevermind i already found the solution to my problem, here if you have same problem like me

private void OnMenuItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var item = (MasterPageItem)e.SelectedItem;
Type page = item.TargetType;
// Detail = new NavigationPage((Page)Activator.CreateInstance(page));
Detail.Navigation.PushAsync((Page)Activator.CreateInstance(page));
IsPresented = false;
}


问:
ELI5: Wireless iAP
I am currently playing around with the pybluez package.  I am able to see a list of services offered.  One of the services offered by my iPhone 7s is something called "Wireless iAP" and "Wireless iAP v2".  What is this? Google doesn't have a clear answer.  Thank you!</p>

答: It seems to be the iPod Accessory Protocol (iAP) for controlling certain iPod features. See point 8 in this document for further information: https://developer.apple.com/hardwaredrivers/BluetoothDesignGuidelines.pdf</p>

Title: ELI5: Wireless iAP


问:
Command Line Calculator in Java ONLY using if else
I've been given this question but I think there's something wrong with my code.

Write a Java Program to take in 3 command line arguments for calculation.
The first and third argument must be an Integer.
The second argument must be either + - x /
The program will print out the result of the calculation if the 3 arguments are correct. Do not use switch, only use if else.

I input the following arguments:

```<code>1 '*' 2
</code>```

And then get "You have entered an invalid operator" as a result. If I remove '*' and replace it in with just *:

```<code>1 * 2
</code>```

My code cannot work at all and I get the following error:

```<code>Exception in thread "main" java.lang.NumberFormatException:

For input string: ".project"

at java.lang.NumberFormatException.forInputString(Unknown Source)

at java.lang.Integer.parseInt(Unknown Source)

at java.lang.Integer.parseInt(Unknown Source)

at Command1.main(Unknown Source)
</code>```

Any idea how I can correct my code? I wondered if I should replace char with String instead but couldn't get the symbol to work either.

Code:

```<code>import java.util.Scanner;
public class Command1 {

public static void main(String[] args) {
    int num1 = Integer.parseInt(args[0]);
    char symbol = args[1].charAt(0);
    int num2 = Integer.parseInt(args[2]);
    System.out.println(args[0]+" "+args[1]+" "+args[2]+" = ");
    if(symbol=='+')
    {
        System.out.println(num1+num2);
    }
    else if(symbol=='-')
    {
        System.out.println(num1-num2);
    }
    else if(symbol=='*')
    {
        System.out.println(num1*num2);
    }
    else if(symbol=='/')
    {
        System.out.println(num1/num2);
    }
    else
    {
        System.out.println("You have entered an invalid operator.");
    }
    // TODO Auto-generated method stub

 }

}
</code>```

答:
Your problem is simply the use of the quotes you are passing as the arguments.

Using ' or no quote will result in the two errors you quote above.

Try using double quotes:

```<code>java Command1 5 "*" 2
</code>```

Body:
I've been given this question but I think there's something wrong with my code.

Write a Java Program to take in 3 command line arguments for calculation.
The first and third argument must be an Integer.
The second argument must be either + - x /
The program will print out the result of the calculation if the 3 arguments are correct. Do not use switch, only use if else.

I input the following arguments:

1 '*' 2

And then get "You have entered an invalid operator" as a result. If I remove '*' and replace it in with just *:

1 * 2

My code cannot work at all and I get the following error:

Exception in thread "main" java.lang.NumberFormatException:

For input string: ".project"

at java.lang.NumberFormatException.forInputString(Unknown Source)

at java.lang.Integer.parseInt(Unknown Source)

at java.lang.Integer.parseInt(Unknown Source)

at Command1.main(Unknown Source)

Any idea how I can correct my code? I wondered if I should replace char with String instead but couldn't get the symbol to work either.

Code:

import java.util.Scanner;
public class Command1 {

public static void main(String[] args) {
    int num1 = Integer.parseInt(args[0]);
    char symbol = args[1].charAt(0);
    int num2 = Integer.parseInt(args[2]);
    System.out.println(args[0]+" "+args[1]+" "+args[2]+" = ");
    if(symbol=='+')
    {
        System.out.println(num1+num2);
    }
    else if(symbol=='-')
    {
        System.out.println(num1-num2);
    }
    else if(symbol=='*')
    {
        System.out.println(num1*num2);
    }
    else if(symbol=='/')
    {
        System.out.println(num1/num2);
    }
    else
    {
        System.out.println("You have entered an invalid operator.");
    }
    // TODO Auto-generated method stub

 }

}

Body:
Your problem is simply the use of the quotes you are passing as the arguments.

Using ' or no quote will result in the two errors you quote above.

Try using double quotes:

java Command1 5 "*" 2


问:
How to reset selects inside an array without v-model

Problem

I need to reset all selects inside an array that has no v-models within Vue.js.

Template

```<code><div id="app">
  <div v-for="(element, index) in elements">
    <select @input="setElement(index, $event.target.value)">
      <option v-for="option in options" :value="option">{{option}}</option>
    </select>
  </div>

  <button @click="addElement">
    Set three elements
  </button>
</div>
</code>```

Script

```<code>new Vue({
  el: '#app',
  data() {
    return {
      options: ['a', 'b', 'c'],
      elements: [{
        element: ''
      }, {
        element: ''
      }]
    }
  },

  methods: {
    addElement() {
        this.elements = []
        this.elements.push({
          element: ''
        })
        this.elements.push({
          element: ''
        })
        this.elements.push({
          element: ''
        })
      },

      setElement(index, el) {
        let element = {
          element: el
        }

        this.$set(this.elements, index, element)
      }
  }
})
</code>```

Demo: https://jsfiddle.net/jqb99tks/4/

Wish

When the length of elements change (e. g. a reset), the selects should be reset.

Approach

I can iterate through all HTML selects and manually reset them but that feels like a hacked solution.

答:
The reason why it happens it because Vue tries to reuse HTML and prevent expensive rerender it it thinks it's possible to do so. In your case it chooses not to rerender select boxes. To tell framework that you want HTML to be rerendered (like in your case to reset selected value) you just need to use unique key prop which is different from previous rendered value:

```<code><div v-for="(element, index) in elements">
  <select :key="index + elements.length" @input="setElement(index, $event.target.value)">
    <option v-for="option in options" :value="option">{{option}}</option>
  </select>
</div>
</code>```

Note, that I added :key="index + elements.length". elements.length is there to make key depend on length of elements, index alone is not enough as it will be the same, i.e. 0, 1, etc.

Also note, that for it to work you need to revise setElement method as it's doing something weird at the moment, this.$set(this.elements, index, element) is a problem. Change it to something like this:

```<code>setElement(index, value) {
  this.$set(this.elements[index], 'element', value)
}
</code>```

Demo: https://jsfiddle.net/jqb99tks/6/

Body:
Problem

I need to reset all selects inside an array that has no v-models within Vue.js.

Template

    <select @input="setElement(index, $event.target.value)">
      <option v-for="option in options" :value="option">{{option}}</option>
    </select>

  <button @click="addElement">
    Set three elements
  </button>

Script

new Vue({
  el: '#app',
  data() {
    return {
      options: ['a', 'b', 'c'],
      elements: [{
        element: ''
      }, {
        element: ''
      }]
    }
  },

  methods: {
    addElement() {
        this.elements = []
        this.elements.push({
          element: ''
        })
        this.elements.push({
          element: ''
        })
        this.elements.push({
          element: ''
        })
      },

      setElement(index, el) {
        let element = {
          element: el
        }

        this.$set(this.elements, index, element)
      }
  }
})

Demo: https://jsfiddle.net/jqb99tks/4/

Wish

When the length of elements change (e. g. a reset), the selects should be reset.

Approach

I can iterate through all HTML selects and manually reset them but that feels like a hacked solution.

Body:
The reason why it happens it because Vue tries to reuse HTML and prevent expensive rerender it it thinks it's possible to do so. In your case it chooses not to rerender select boxes. To tell framework that you want HTML to be rerendered (like in your case to reset selected value) you just need to use unique key prop which is different from previous rendered value:

<div v-for="(element, index) in elements">
  <select :key="index + elements.length" @input="setElement(index, $event.target.value)">
    <option v-for="option in options" :value="option">{{option}}</option>
  </select>
</div>

Note, that I added :key="index + elements.length". elements.length is there to make key depend on length of elements, index alone is not enough as it will be the same, i.e. 0, 1, etc.

Also note, that for it to work you need to revise setElement method as it's doing something weird at the moment, this.$set(this.elements, index, element) is a problem. Change it to something like this:

setElement(index, value) {
  this.$set(this.elements[index], 'element', value)
}

Demo: https://jsfiddle.net/jqb99tks/6/


问:
LinqPad query runs fine, but fails with Linq to Entities error running in visual studio
I have created a query for testing in LinqPad, I do not think the query is anything special, but it does execute a function stored in the database.

I have included the query here:

```<code>var opps = (from o in Entities.Table1
                        join oa in Entities.Table2 on o.Id equals oa.Table1Id
                        where (o.StatusId == 1)
                        && oa.UserId == userId
                        select new
                        {
                            ID = o.Id,
                            Options = Entities.GetOptions(o.Id),
                            LastUpdated = o.UpdatedDate
                        }).ToList();
</code>```

Now, running this within LinqPad, no errors are produced, but if I run the same code within a function in my c# project I get the following error message.

```<code>LINQ to Entities does not recognize the method 'System.Linq.IQueryable`1[Dal.GetOptionsReturnModel] GetOptions(System.Nullable`1[System.Int64])' method, and this method cannot be translated into a store expression.
</code>```

Commenting out the line:

```<code>*Options = Entities.GetOptions(o.Id),*
</code>```

Fixes the problem, so I know it is to do with this, but I cannot figure out why it works in LinqPad.

Update

GetOptions is a function within the sql server database.

Update 2

Thanks for the replies, I did notice that I did not place the error on this question. Right to rectify that now.

The original error message was

```<code>LINQ to Entities does not recognize the method 'System.Linq.IQueryable`1[Dal.GetOptionsReturnModel] GetOptions(System.Nullable`1[System.Int64])' method, and this method cannot be translated into a store expression.
</code>```

After applying the IEnumerable, the error changes to:

```<code>"System.Data.Entity.Core.EntityCommandExecutionException",
"An error occurred while executing the command definition. See the inner exception for details.",
"There is already an open DataReader associated with this Command which must be closed first.",
"   at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)\r\n   at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)\r\n
</code>```

Update 3

Not sure if it helps, but in Visual Studio, I am using EF 6.0.0

答:
still not sure as to what caused this, but I think it had something to do with upgrading EF.POCO.Generator Add-in. I created a new ClassLibrary and when using v2.33.0 of the Add-in, all works fine. </p>

<p>The issues came from the v2.23.0 version of the Add-In. </p>

Body:
I have created a query for testing in LinqPad, I do not think the query is anything special, but it does execute a function stored in the database.

I have included the query here:

var opps = (from o in Entities.Table1
                        join oa in Entities.Table2 on o.Id equals oa.Table1Id
                        where (o.StatusId == 1)
                        && oa.UserId == userId
                        select new
                        {
                            ID = o.Id,
                            Options = Entities.GetOptions(o.Id),
                            LastUpdated = o.UpdatedDate
                        }).ToList();

Now, running this within LinqPad, no errors are produced, but if I run the same code within a function in my c# project I get the following error message.

LINQ to Entities does not recognize the method 'System.Linq.IQueryable`1[Dal.GetOptionsReturnModel] GetOptions(System.Nullable`1[System.Int64])' method, and this method cannot be translated into a store expression.

Commenting out the line:

*Options = Entities.GetOptions(o.Id),*

Fixes the problem, so I know it is to do with this, but I cannot figure out why it works in LinqPad.

Update

GetOptions is a function within the sql server database.

Update 2

Thanks for the replies, I did notice that I did not place the error on this question. Right to rectify that now.

The original error message was

LINQ to Entities does not recognize the method 'System.Linq.IQueryable`1[Dal.GetOptionsReturnModel] GetOptions(System.Nullable`1[System.Int64])' method, and this method cannot be translated into a store expression.

After applying the IEnumerable, the error changes to:

"System.Data.Entity.Core.EntityCommandExecutionException",
"An error occurred while executing the command definition. See the inner exception for details.",
"There is already an open DataReader associated with this Command which must be closed first.",
"   at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)\r\n   at System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)\r\n

Update 3

Not sure if it helps, but in Visual Studio, I am using EF 6.0.0

Body:
still not sure as to what caused this, but I think it had something to do with upgrading EF.POCO.Generator Add-in. I created a new ClassLibrary and when using v2.33.0 of the Add-in, all works fine.

The issues came from the v2.23.0 version of the Add-In.


答:
Try to replace

```<code>_btnShowData.titleLabel.text = [NSString stringWithFormat:@"%@",oneCustomer];
</code>```

with

```<code>[_btnShowData setTitle:[NSString stringWithFormat:@"%@",oneCustomer] forState:UIControlStateNormal];
</code>```

Title: Show elements of array in button text in Objective-C

Body:
Try to replace

_btnShowData.titleLabel.text = [NSString stringWithFormat:@"%@",oneCustomer];

with

[_btnShowData setTitle:[NSString stringWithFormat:@"%@",oneCustomer] forState:UIControlStateNormal];


问:
How to encode UTF8 filename for HTTP headers? (Python, Django)
I have problem with HTTP headers, they're encoded in ASCII and I want to provided a view for downloading files that names can be non ASCII.

```<code>response['Content-Disposition'] = 'attachment; filename="%s"' % (vo.filename.encode("ASCII","replace"), )
</code>```

I don't want to use static files serving for same issue with non ASCII file names but in this case there would be a problem with File system and it's file name encoding. (I don't know target os.)

I've already tried urllib.quote(), but it raises KeyError exception.

Possibly I'm doing something wrong but maybe it's impossible.

答:
I can say that I've had success using the newer (RFC 5987) format of specifying a header encoded with the e-mail form (RFC 2231). I came up with the following solution which is based on code from the django-sendfile project.

```<code>import unicodedata
from django.utils.http import urlquote

def rfc5987_content_disposition(file_name):
    ascii_name = unicodedata.normalize('NFKD', file_name).encode('ascii','ignore').decode()
    header = 'attachment; filename="{}"'.format(ascii_name)
    if ascii_name != file_name:
        quoted_name = urlquote(file_name)
        header += '; filename*=UTF-8\'\'{}'.format(quoted_name)

    return header

# e.g.
  # request['Content-Disposition'] = rfc5987_content_disposition(file_name)
</code>```

I have only tested my code on Python 3.4 with Django 1.8. So the similar solution in django-sendfile may suite you better.

There's a long standing ticket in Django's tracker which acknowledges this but no patches have yet been proposed afaict. So unfortunately this is as close to using a robust tested library as I could find, please let me know if there's a better solution.

Body:
I have problem with HTTP headers, they're encoded in ASCII and I want to provided a view for downloading files that names can be non ASCII.

response['Content-Disposition'] = 'attachment; filename="%s"' % (vo.filename.encode("ASCII","replace"), )

I don't want to use static files serving for same issue with non ASCII file names but in this case there would be a problem with File system and it's file name encoding. (I don't know target os.)

I've already tried urllib.quote(), but it raises KeyError exception.

Possibly I'm doing something wrong but maybe it's impossible.

Body:
I can say that I've had success using the newer (RFC 5987) format of specifying a header encoded with the e-mail form (RFC 2231). I came up with the following solution which is based on code from the django-sendfile project.

import unicodedata
from django.utils.http import urlquote

def rfc5987_content_disposition(file_name):
    ascii_name = unicodedata.normalize('NFKD', file_name).encode('ascii','ignore').decode()
    header = 'attachment; filename="{}"'.format(ascii_name)
    if ascii_name != file_name:
        quoted_name = urlquote(file_name)
        header += '; filename*=UTF-8\'\'{}'.format(quoted_name)

    return header

# e.g.
  # request['Content-Disposition'] = rfc5987_content_disposition(file_name)

I have only tested my code on Python 3.4 with Django 1.8. So the similar solution in django-sendfile may suite you better.

There's a long standing ticket in Django's tracker which acknowledges this but no patches have yet been proposed afaict. So unfortunately this is as close to using a robust tested library as I could find, please let me know if there's a better solution.


问:
How can I create an iOS style PIN/password box with CSS?
I want to create a html5 input that looks like the iOS enter Pin (on the lock screen).... with 4 input boxes.

How do i achieve this?

I tried the following:

1) Created a normal input box.

2) Removed its borders.

3) Placed the above image as the background of the input box.

4) And added some letter spacing.

Problem is: As i type the first 3 characters, it fits in the boxes:

But when i type the 4th character, the characters move towards the left and hence it appears as below:

What can I do to fix this ?

Any other better approach ??

EDIT:

Ok based on the below answers, I modified the approach to have 4 input boxes. And on keyup event for each input box, I change the focus to next input box.

This works well on browser. But does not work on the device (iPhone 5). What is the problem ?

It is a Sencha Touch app packaged using Cordova.

SOLVED:

Need to disable <preference name="KeyboardDisplayRequiresUserAction" value="false" />

答:
```<code> <input type="tel" maxlength="1" tabindex="1" class="display-otp-box" data-key="otp1">
 <input type="tel" maxlength="1" tabindex="2" class="display-otp-box" data-key="otp2">
 <input type="tel" maxlength="1" tabindex="3" class="display-otp-box" data-key="otp3">
 <input type="tel" maxlength="1" tabindex="4" class="display-otp-box" data-key="otp4">

$('.display-otp-box').on('keyup', function (e) {
  var key = event.keyCode || event.charCode;

  /* for backspace, focus will move to the previous box */
  if( key === 8 || key === 46 ){
     $(this).prev('input').focus();
     return;
  }
  $(this).next('input').focus();
 });
</code>```

type="tel" on the input will make sure the numeric keypad appears when using on the phone

next input will be focused automatically with the help of tabindex.

Body:
 <input type="tel" maxlength="1" tabindex="1" class="display-otp-box" data-key="otp1">
 <input type="tel" maxlength="1" tabindex="2" class="display-otp-box" data-key="otp2">
 <input type="tel" maxlength="1" tabindex="3" class="display-otp-box" data-key="otp3">
 <input type="tel" maxlength="1" tabindex="4" class="display-otp-box" data-key="otp4">

$('.display-otp-box').on('keyup', function (e) {
  var key = event.keyCode || event.charCode;

  /* for backspace, focus will move to the previous box */
  if( key === 8 || key === 46 ){
     $(this).prev('input').focus();
     return;
  }
  $(this).next('input').focus();
 });

type="tel" on the input will make sure the numeric keypad appears when using on the phone

next input will be focused automatically with the help of tabindex.


问:
Inject ViewModelFactory.Provider in activity for espresso testing
Related to this question: Espresso, Dagger2 set ViemodelProvider.Factory on BaseActivity

I went through hell and back to get a ViewModelFactory.Provider on an Activity during my tests, in order to get espresso tests working regarding Android Architecture Components. I expected it to be simple, but I guess it's not...

The example to get it working with fragments is straightforward:

https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/androidTest/java/com/android/example/github/ui/user/UserFragmentTest.java

```<code>@Before
public void init() {
    UserFragment fragment = UserFragment.create("foo");
    viewModel = mock(UserViewModel.class);
    when(viewModel.getUser()).thenReturn(userData);
    when(viewModel.getRepositories()).thenReturn(repoListData);
    navigationController = mock(NavigationController.class);
    fragmentBindingAdapters = mock(FragmentBindingAdapters.class);

    fragment.viewModelFactory = ViewModelUtil.createFor(viewModel);
    fragment.navigationController = navigationController;
    fragment.dataBindingComponent = () -> fragmentBindingAdapters;

    activityRule.getActivity().setFragment(fragment);
}
</code>```

However, this simply won't work with activities as I can't get the dependencies on the activity before its creation using an ActivityTestRule.

I followed the same new dependency injection flow with Dagger2 as in the example above using the HasActivityInjector interface.

I would appreciate your help!

答:
It’s possible to set injected activity attribute by registering a custom ActivityLifecycleCallbacks in your TestApp in the @Before Method.

Example:

```<code> @Before
public void init(){

    UserFragment fragment = UserFragment.create("foo");
    viewModel = mock(UserViewModel.class);
    when(viewModel.getUser()).thenReturn(userData);
    when(viewModel.getRepositories()).thenReturn(repoListData);
    navigationController = mock(NavigationController.class);

    TestApp testApp = ((TestApp) InstrumentationRegistry.getContext().getApplicationContext());
    testApp.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            //will be called before the onCreate method of your activity
            activity.setViewModelFactory(ViewModelUtil.createFor(viewModel));
        }

        @Override
        public void onActivityStarted(Activity activity) {

        }

        @Override
        public void onActivityResumed(Activity activity) {

        }

        @Override
        public void onActivityPaused(Activity activity) {

        }

        @Override
        public void onActivityStopped(Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

        }

        @Override
        public void onActivityDestroyed(Activity activity) {

        }
    });

    fragment.viewModelFactory = ViewModelUtil.createFor(viewModel);
    fragment.navigationController = navigationController;
    fragment.dataBindingComponent = () -> fragmentBindingAdapters;

    activityRule.getActivity().setFragment(fragment);

}
</code>```

Body:
Related to this question: Espresso, Dagger2 set ViemodelProvider.Factory on BaseActivity

I went through hell and back to get a ViewModelFactory.Provider on an Activity during my tests, in order to get espresso tests working regarding Android Architecture Components. I expected it to be simple, but I guess it's not...

The example to get it working with fragments is straightforward:

https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/src/androidTest/java/com/android/example/github/ui/user/UserFragmentTest.java

@Before
public void init() {
    UserFragment fragment = UserFragment.create("foo");
    viewModel = mock(UserViewModel.class);
    when(viewModel.getUser()).thenReturn(userData);
    when(viewModel.getRepositories()).thenReturn(repoListData);
    navigationController = mock(NavigationController.class);
    fragmentBindingAdapters = mock(FragmentBindingAdapters.class);

    fragment.viewModelFactory = ViewModelUtil.createFor(viewModel);
    fragment.navigationController = navigationController;
    fragment.dataBindingComponent = () -> fragmentBindingAdapters;

    activityRule.getActivity().setFragment(fragment);
}

However, this simply won't work with activities as I can't get the dependencies on the activity before its creation using an ActivityTestRule.

I followed the same new dependency injection flow with Dagger2 as in the example above using the HasActivityInjector interface.

I would appreciate your help!

Body:
It’s possible to set injected activity attribute by registering a custom ActivityLifecycleCallbacks in your TestApp in the @Before Method.

Example:

 @Before
public void init(){

    UserFragment fragment = UserFragment.create("foo");
    viewModel = mock(UserViewModel.class);
    when(viewModel.getUser()).thenReturn(userData);
    when(viewModel.getRepositories()).thenReturn(repoListData);
    navigationController = mock(NavigationController.class);

    TestApp testApp = ((TestApp) InstrumentationRegistry.getContext().getApplicationContext());
    testApp.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            //will be called before the onCreate method of your activity
            activity.setViewModelFactory(ViewModelUtil.createFor(viewModel));
        }

        @Override
        public void onActivityStarted(Activity activity) {

        }

        @Override
        public void onActivityResumed(Activity activity) {

        }

        @Override
        public void onActivityPaused(Activity activity) {

        }

        @Override
        public void onActivityStopped(Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

        }

        @Override
        public void onActivityDestroyed(Activity activity) {

        }
    });

    fragment.viewModelFactory = ViewModelUtil.createFor(viewModel);
    fragment.navigationController = navigationController;
    fragment.dataBindingComponent = () -> fragmentBindingAdapters;

    activityRule.getActivity().setFragment(fragment);

}


问:
Is there a name for this type of popular footer?
Screenshot of a footer:

I'm unsure if there is a particular name for that kind of footer or if it's a widget for a certain framework. That particular example was taken from buffalonews.com

After I know the name I can refine my searching for implementing it. Thank you for your input.

答:
I don't think there is actually a name for this king of footer though I agree it is quite common.

Maybe it is because this "kind" is very subjective and would have to be very specific and most of the times not helpful. (Or maybe because nobody has coined it yet) :)

Look at Brad's answer

If you have wordpress you could see some here for inspiration. In wordpress and the popular CMS you can change the footer for many available ones.


问:
Group elements in an Associative arrays without altering the squence
I have following array

```<code>[0] => Array (
    [subscriptionId] => 32
    [subscribedTo] => 20
    [subscriptionDate] => 2017-11-11 11:01:20
    [videoTime] => 2017-11-11 10:54:44
    )
[1] => Array (
    [subscriptionId] => 30
    [subscribedTo] => 2
    [subscriptionDate] => 2017-11-11 10:27:32
    [videoTime] => 2017-11-10 21:43:03
    )
[2] => Array (
    [subscriptionId] => 30
    [subscribedTo] => 2
    [subscriptionDate] => 2017-11-11 10:27:32
    [videoTime] => 2017-11-10 21:38:36
    )
[3] => Array (
    [subscriptionId] => 31
    [subscribedTo] => 7
    [subscriptionDate] => 2017-11-11 10:28:29
    [videoTime] => 2017-10-26 12:41:23
    )
[4] => Array (
    [subscriptionId] => 31
    [subscribedTo] => 7
    [subscriptionDate] => 2017-11-11 10:28:29
    [videoTime] => 2017-10-26 12:29:02
          )
[5] => Array (
    [subscriptionId] => 31
    [subscribedTo] => 7
    [subscriptionDate] => 2017-11-11 10:28:29
    [videoTime] => 2017-10-26 12:23:26
    )
[6] => Array (
    [subscriptionId] => 30
    [subscribedTo] => 2
    [subscriptionDate] => 2017-11-11 10:27:32
    [videoTime] => 2017-10-09 09:23:59
    )
[7] => Array (
    [subscriptionId] => 30
    [subscribedTo] => 2
    [subscriptionDate] => 2017-11-11 10:27:32
    [videoTime] => 2017-10-09 09:23:35
    )
</code>```

I want to group the rows based on subscribedTo such that the sequence does not change.
I found a solution here
but it results in following sequence based on subscribedId:
2,2,2,2,7,7,7,20

What I am trying to get is:
20,2,2,2,2,7,7,7

答:
Try this, first group equal indices and then merging</p>

```<code>$arr = [];// this should be your array
$temp = [];

foreach ($arr as $a) {
    if (!isset($temp[$a[subscribedTo]])) {
        $temp[$a[subscribedTo]] = [];
    }

    $temp[$a[subscribedTo]][] = $a;
}

$arr = []; //reset the array
foreach ($temp as $t) {
    array_merge($arr, $t);
}
</code>```

Body:
I have following array

[0] => Array (
    [subscriptionId] => 32
    [subscribedTo] => 20
    [subscriptionDate] => 2017-11-11 11:01:20
    [videoTime] => 2017-11-11 10:54:44
    )
[1] => Array (
    [subscriptionId] => 30
    [subscribedTo] => 2
    [subscriptionDate] => 2017-11-11 10:27:32
    [videoTime] => 2017-11-10 21:43:03
    )
[2] => Array (
    [subscriptionId] => 30
    [subscribedTo] => 2
    [subscriptionDate] => 2017-11-11 10:27:32
    [videoTime] => 2017-11-10 21:38:36
    )
[3] => Array (
    [subscriptionId] => 31
    [subscribedTo] => 7
    [subscriptionDate] => 2017-11-11 10:28:29
    [videoTime] => 2017-10-26 12:41:23
    )
[4] => Array (
    [subscriptionId] => 31
    [subscribedTo] => 7
    [subscriptionDate] => 2017-11-11 10:28:29
    [videoTime] => 2017-10-26 12:29:02
          )
[5] => Array (
    [subscriptionId] => 31
    [subscribedTo] => 7
    [subscriptionDate] => 2017-11-11 10:28:29
    [videoTime] => 2017-10-26 12:23:26
    )
[6] => Array (
    [subscriptionId] => 30
    [subscribedTo] => 2
    [subscriptionDate] => 2017-11-11 10:27:32
    [videoTime] => 2017-10-09 09:23:59
    )
[7] => Array (
    [subscriptionId] => 30
    [subscribedTo] => 2
    [subscriptionDate] => 2017-11-11 10:27:32
    [videoTime] => 2017-10-09 09:23:35
    )

I want to group the rows based on subscribedTo such that the sequence does not change.
I found a solution here
but it results in following sequence based on subscribedId:
2,2,2,2,7,7,7,20

What I am trying to get is:
20,2,2,2,2,7,7,7

Body:
Try this, first group equal indices and then merging

$arr = [];// this should be your array
$temp = [];

foreach ($arr as $a) {
    if (!isset($temp[$a[subscribedTo]])) {
        $temp[$a[subscribedTo]] = [];
    }

    $temp[$a[subscribedTo]][] = $a;
}

$arr = []; //reset the array
foreach ($temp as $t) {
    array_merge($arr, $t);
}


问:
Change row color based on a value (inside the row)
I have this grid

```<code>{
        xtype: 'gridpanel',
        id: 'grdSeguimiento',
        margin: '20 0 10 0',
        width: 1423,
        store: 'Solicitud',
        viewConfig: {
            getRowClass: function(record, rowIndex, rowParams, store) {
                console.log(record);
                return record.data.get('TIEMPO') == 1 ? 'child-row' : 'adult-row';

            },
            stripeRows: false
        },
        columns: [

            {
                xtype: 'gridcolumn',
                hidden: true,
                dataIndex: 'TIEMPO',
                hideable: false
            }
        ],
        plugins: [
            {
                ptype: 'rowediting',
                listeners: {
                    edit: 'onRowEditingEdit'
                }
            }
        ]
    }
</code>```

And this css file

```<code>.child-row .x-grid-cell {
background-color: #ffe2e2 !important;
color: #900;
}

.adult-row .x-grid-cell {
background-color: #e2ffe2 !important;
color: #090;
 }
</code>```

I just want each row to have a color based on a value (TIEMPO) inside each row.

But I am getting the

```<code>Error: rendered block refreshed at 0 rows while BufferedRenderer view size is 63
</code>```

The grid worked fine before using the css file. I made some research but couldn't find anything useful.

The code above is not all the code, I used renderer and action columns but I gues that is not so important.

Any ideas?

Edit 1: If I change the table to non sortable the data appears but without any styling

答:
Any ideas?

You need to change in your current code instead of
 this record.data.get('TIEMPO') you need to use record.get('TIEMPO') or record.data.TIEMPO for more details you can refer this Ext.data.Model get().

Here I have created an small sencha fiddle demo. You can see it is working fine here.

```<code>Ext.create('Ext.data.Store', {
    storeId: 'simpsonsStore',
    fields: ['name', 'email', 'phone', 'isChecked'],
    data: {
        'items': [{
            'name': 'Lisa',
            "email": "lisa@simpsons.com",
            "phone": "555-111-1224",
            "isChecked": 1
        }, {
            'name': 'Bart',
            "email": "bart@simpsons.com",
            "phone": "555-222-1234",
            "isChecked": 0
        }, {
            'name': 'Homer',
            "email": "homer@simpsons.com",
            "phone": "555-222-1244",
            "isChecked": 0
        }, {
            'name': 'Marge',
            "email": "marge@simpsons.com",
            "phone": "555-222-1254",
            "isChecked": 1
        }]
    },
    proxy: {
        type: 'memory',
        reader: {
            type: 'json',
            root: 'items'
        }
    }
});

Ext.create('Ext.grid.Panel', {
    title: 'Grid row class on basis for row value..',
    store: Ext.data.StoreManager.lookup('simpsonsStore'),
    viewConfig: {
        getRowClass: function (record, rowIndex, rowParams, store) {
            return record.get('isChecked') == 1 ? 'child-row' : 'adult-row';
            //you can also use
            //record.data.isChecked == 1 ? 'child-row' : 'adult-row';

        },
        stripeRows: false
    },
    columns: [{
        text: 'Name',
        dataIndex: 'name',
        flex: 1
    }, {
        text: 'Email',
        dataIndex: 'email',
        flex: 1
    }, {
        text: 'Phone',
        dataIndex: 'phone',
        flex: 1
    }],
    height: 200,
    // width: 400,
    renderTo: Ext.getBody()
});
</code>```

Body:
I have this grid

{
        xtype: 'gridpanel',
        id: 'grdSeguimiento',
        margin: '20 0 10 0',
        width: 1423,
        store: 'Solicitud',
        viewConfig: {
            getRowClass: function(record, rowIndex, rowParams, store) {
                console.log(record);
                return record.data.get('TIEMPO') == 1 ? 'child-row' : 'adult-row';

            },
            stripeRows: false
        },
        columns: [

            {
                xtype: 'gridcolumn',
                hidden: true,
                dataIndex: 'TIEMPO',
                hideable: false
            }
        ],
        plugins: [
            {
                ptype: 'rowediting',
                listeners: {
                    edit: 'onRowEditingEdit'
                }
            }
        ]
    }

And this css file

.child-row .x-grid-cell {
background-color: #ffe2e2 !important;
color: #900;
}

.adult-row .x-grid-cell {
background-color: #e2ffe2 !important;
color: #090;
 }

I just want each row to have a color based on a value (TIEMPO) inside each row.

But I am getting the

Error: rendered block refreshed at 0 rows while BufferedRenderer view size is 63

The grid worked fine before using the css file. I made some research but couldn't find anything useful.

The code above is not all the code, I used renderer and action columns but I gues that is not so important.

Any ideas?

Edit 1: If I change the table to non sortable the data appears but without any styling

Body:
Any ideas?

You need to change in your current code instead of
 this record.data.get('TIEMPO') you need to use record.get('TIEMPO') or record.data.TIEMPO for more details you can refer this Ext.data.Model get().

Here I have created an small sencha fiddle demo. You can see it is working fine here.

Ext.create('Ext.data.Store', {
    storeId: 'simpsonsStore',
    fields: ['name', 'email', 'phone', 'isChecked'],
    data: {
        'items': [{
            'name': 'Lisa',
            "email": "lisa@simpsons.com",
            "phone": "555-111-1224",
            "isChecked": 1
        }, {
            'name': 'Bart',
            "email": "bart@simpsons.com",
            "phone": "555-222-1234",
            "isChecked": 0
        }, {
            'name': 'Homer',
            "email": "homer@simpsons.com",
            "phone": "555-222-1244",
            "isChecked": 0
        }, {
            'name': 'Marge',
            "email": "marge@simpsons.com",
            "phone": "555-222-1254",
            "isChecked": 1
        }]
    },
    proxy: {
        type: 'memory',
        reader: {
            type: 'json',
            root: 'items'
        }
    }
});

Ext.create('Ext.grid.Panel', {
    title: 'Grid row class on basis for row value..',
    store: Ext.data.StoreManager.lookup('simpsonsStore'),
    viewConfig: {
        getRowClass: function (record, rowIndex, rowParams, store) {
            return record.get('isChecked') == 1 ? 'child-row' : 'adult-row';
            //you can also use
            //record.data.isChecked == 1 ? 'child-row' : 'adult-row';

        },
        stripeRows: false
    },
    columns: [{
        text: 'Name',
        dataIndex: 'name',
        flex: 1
    }, {
        text: 'Email',
        dataIndex: 'email',
        flex: 1
    }, {
        text: 'Phone',
        dataIndex: 'phone',
        flex: 1
    }],
    height: 200,
    // width: 400,
    renderTo: Ext.getBody()
});