问:
How to put session value store into database?
I wanted to retrieve session array and put into other model But throws `

Call to a member function pluck() on array

Controller I used :

```<code>$orders =  $request->session()->get('order');
$order = new Order();
$order->school_id = $orders->pluck('school_id');
$order->order_date = $orders->pluck('order_date');
$order->time_slot = $orders->pluck('time_slot');
</code>```

How do i access the session data and put into other model?

Here is the response I get when i dd() the session :

```<code>array:1 [▼
  0 => array:3 [▼
    "school_id" => "4"
    "order_date" => "11/25/2017"
    "time_slot" => "10am - 8pm"
  ]
]
</code>```

答:
Call to a member function pluck() on array

Your $orders variable is an array so you can't use pluck. You can do $order['key'] to access their values. Or as others suggested, use the helper function array_get

Body:
I wanted to retrieve session array and put into other model But throws `

Call to a member function pluck() on array

Controller I used :

$orders =  $request->session()->get('order');
$order = new Order();
$order->school_id = $orders->pluck('school_id');
$order->order_date = $orders->pluck('order_date');
$order->time_slot = $orders->pluck('time_slot');

How do i access the session data and put into other model?

Here is the response I get when i dd() the session :

array:1 [▼
  0 => array:3 [▼
    "school_id" => "4"
    "order_date" => "11/25/2017"
    "time_slot" => "10am - 8pm"
  ]
]


来源: stackexchange

问:
python one line for loop over a function returning a tuple
I've tried searching quite a lot on this one, but being relatively new to python I feel I am missing the required terminology to find what I'm looking for.

I have a function:

```<code>def my_function(x,y):
    # code...
    return(a,b,c)
</code>```

Where x and y are numpy arrays of length 2000 and the return values are integers. I'm looking for a shorthand (one-liner) to loop over this function as such:

```<code>Output = [my_function(X[i],Y[i]) for i in range(len(Y))]
</code>```

Where X and Y are of the shape (135,2000). However, after running this I am currently having to do the following to separate out 'Output' into three numpy arrays.

```<code>Output = np.asarray(Output)
a = Output.T[0]
b = Output.T[1]
c = Output.T[2]
</code>```

Which I feel isn't the best practice. I have tried:

```<code>(a,b,c) = [my_function(X[i],Y[i]) for i in range(len(Y))]
</code>```

But this doesn't seem to work. Does anyone know a quick way around my problem?

答:
my_function(X[i], Y[i]) for i in range(len(Y))

On the verge of crossing the "opinion-based" border, ...Y[i]... for i in range(len(Y)) is usually a big no-no in Python. It is even a bigger no-no when working with numpy arrays. One of the advantages of working with numpy is the 'vectorization' that it provides, and thus pushing the for loop down to the C level rather than the (slower) Python level.

So, if you rewrite my_function so it can handle the arrays in a vectorized fashion using the multiple tools and methods that numpy provides, you may not even need that "one-liner" you are looking for.

ContentLicense: CC BY-SA 3.0

Body:
I've tried searching quite a lot on this one, but being relatively new to python I feel I am missing the required terminology to find what I'm looking for.

I have a function:

def my_function(x,y):
    # code...
    return(a,b,c)

Where x and y are numpy arrays of length 2000 and the return values are integers. I'm looking for a shorthand (one-liner) to loop over this function as such:

Output = [my_function(X[i],Y[i]) for i in range(len(Y))]

Where X and Y are of the shape (135,2000). However, after running this I am currently having to do the following to separate out 'Output' into three numpy arrays.

Output = np.asarray(Output)
a = Output.T[0]
b = Output.T[1]
c = Output.T[2]

Which I feel isn't the best practice. I have tried:

(a,b,c) = [my_function(X[i],Y[i]) for i in range(len(Y))]

But this doesn't seem to work. Does anyone know a quick way around my problem?


问:
Using Java in ReactNative
I'm new in ReactNative, and I want to import a Java class into my ReactNative project. Is that possible? How should I do that?

The Java class includes using of Java BigInteger:

```<code>public java.math.BigInteger randomPrimeBigInteger(int bitlen, int certainty, java.util.Random rng) {

       return new java.math.BigInteger(bitlen, certainty, rng);
}
</code>```

答: You can write this Java code at the Android's end and call this method from your JS side after creating a wrapper which can communicate to/fro native side.</p>

Title: Using Java in ReactNative

Body:
I'm new in ReactNative, and I want to import a Java class into my ReactNative project. Is that possible? How should I do that?

The Java class includes using of Java BigInteger:

public java.math.BigInteger randomPrimeBigInteger(int bitlen, int certainty, java.util.Random rng) {

       return new java.math.BigInteger(bitlen, certainty, rng);
}


问:
XMPP server in python
I'm looking hard but I cannot find any XMPP server in python with the following features:

using epoll, just like http://www.gevent.org/

supporting BOSH

modular design

use little RAM/CPU for up to 1000 users

more important than the previous requirement: the CPU/RAM usage must be predictable

Prosody looks quite good feature-wise, but I don't know how many users it can support simultaneously and how it is performance-wise.

Could someone give me an idea?

答:
xmpp.org uses Prosody, any other questions? :P

btw, if you want to toy with it a little, you can always run prosody using luajit (didn't test that myself, but I'm fairly sure it would work). Expect at least 2-4x faster execution.

Look @ ejabberd too.

ContentLicense: CC BY-SA 2.5

Title: XMPP server in python


问:
How to change zoom dynamically with many map marker in sebm google maps?
my html code is

```<code><sebm-google-map [latitude]="lat" [longitude]="lng" [zoom]="zoom" [mapTypeControl]="true">
  <sebm-google-map-marker *ngFor="let device of devices;" [latitude]="device.latitude" [longitude]="device.longitude" [label]="device.name">
  </sebm-google-map-marker>
</sebm-google-map>
</code>```

In sebm-google-map I can find fitBounds but do not know how to apply it. I have many devices with map markers so when I load that map component it will show all devices on the map.

答:
First, you are using (I think) an old version of angular-google-maps.

The attribute sebm-google-map is renamed to agm-map.

Example

```<code><agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom">
</agm-map>
</code>```

The fitBounds attribute is a LatLngBoundsLiteral object.

You can define the bounds like this:

```<code>let bounds = {
  east: 12.345,
  north: 23.456,
  south: 34.567,
  west: 45.678
}
</code>```

Body:
my html code is

<sebm-google-map [latitude]="lat" [longitude]="lng" [zoom]="zoom" [mapTypeControl]="true">
  <sebm-google-map-marker *ngFor="let device of devices;" [latitude]="device.latitude" [longitude]="device.longitude" [label]="device.name">
  </sebm-google-map-marker>
</sebm-google-map>

In sebm-google-map I can find fitBounds but do not know how to apply it. I have many devices with map markers so when I load that map component it will show all devices on the map.

Body:
First, you are using (I think) an old version of angular-google-maps.

The attribute sebm-google-map is renamed to agm-map.

Example

<agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom">
</agm-map>

The fitBounds attribute is a LatLngBoundsLiteral object.

You can define the bounds like this:

let bounds = {
  east: 12.345,
  north: 23.456,
  south: 34.567,
  west: 45.678
}


问:
C Program not exiting input mode

I'm trying to find out the number of tabs, spaces and newlines in my C program. The code is :

```<code>#include <stdio.h>

void main()
{
    char c;
    int tabs=0 , spaces=0 , nl=0 ;
    printf("Provide the input");
    scanf("%c" , &c);
    while(c != EOF)
    {
        if(c == ' ')
        spaces++;
        else if(c == '\n')
        nl++;
        else if(c == '\t')
        tabs++;
        scanf("%c" , &c);
    }
    printf("blanks:%d\nspaces:%d\nnewlines:%d" , spaces , tabs , nl);
}
</code>```

Well, I'm expecting it to do just that but the code is just not moving beyond accepting the input phase. What am I doing wrong? Below is what my command line looks like:

```<code>[tejas@localhost The_C_Programming_Language]$ cc Exercise_1-8.c

[tejas@localhost The_C_Programming_Language]$ ./a.out

Provide the input seguiofgawie

gweuigwh

e u w   f qw[uwf
[PHWUO FEFF
qah fuwpfyh fweor
</code>```

(I keep pressing the Return key but to no end. Please help. Thank you for reading. This is my first question, hope i didn't do anything wrong...)

EDIT: getchar() doesn't work either, and I'm currently using Fedora 26 and GEDIT as my text editor

EDIT: getchar() works, in order to send the EOF character, one should press Ctrl+D on an empty line and if you want it done in with just one press of the RETURN key, change your loop condition to variable != '\n'. I apologize for spreading misinformation.

答:
There is a small error here that you are commiting, by comparing the scanned char value to EOF. Quoting another answer

EOF is a macro which expands to an integer constant expression with type int and an implementation dependent negative value but is very commonly -1.

However, since you are reading from stdin, you won't be able to enter it as a single char since it will be considered as 2 characters and will not produce the desired result.
In a nutshell, your program is behaving in the desired way. In order for it to exit input mode, just change your while condition to something which you are able to meet.

Title: C Program not exiting input mode

Body:
I'm trying to find out the number of tabs, spaces and newlines in my C program. The code is :

#include <stdio.h>

void main()
{
    char c;
    int tabs=0 , spaces=0 , nl=0 ;
    printf("Provide the input");
    scanf("%c" , &c);
    while(c != EOF)
    {
        if(c == ' ')
        spaces++;
        else if(c == '\n')
        nl++;
        else if(c == '\t')
        tabs++;
        scanf("%c" , &c);
    }
    printf("blanks:%d\nspaces:%d\nnewlines:%d" , spaces , tabs , nl);
}

Well, I'm expecting it to do just that but the code is just not moving beyond accepting the input phase. What am I doing wrong? Below is what my command line looks like:

[tejas@localhost The_C_Programming_Language]$ cc Exercise_1-8.c

[tejas@localhost The_C_Programming_Language]$ ./a.out

Provide the input seguiofgawie

gweuigwh

e u w   f qw[uwf
[PHWUO FEFF
qah fuwpfyh fweor

(I keep pressing the Return key but to no end. Please help. Thank you for reading. This is my first question, hope i didn't do anything wrong...)

EDIT: getchar() doesn't work either, and I'm currently using Fedora 26 and GEDIT as my text editor

EDIT: getchar() works, in order to send the EOF character, one should press Ctrl+D on an empty line and if you want it done in with just one press of the RETURN key, change your loop condition to variable != '\n'. I apologize for spreading misinformation.


问:
How can I remove [save?, overwrite?, keep CSV format? prompts] while saving .CSV file?
In general the problem I have is that whenever my code comes to an end (see below) it:

Asks whether or not to save changes to .csv
When I click "Yes", it opens the window with location of the file, where I have to select "Save"

Asks whether or not to overwrite the file

Asks whether or not to maintain CSV format

Can you advise how can I remove above prompts [simultaneously having this file saved/overwriting the old version]?

```<code>Sub Test()
Application.ScreenUpdating = False
Application.DisplayAlerts = False

****rest of the code***

   WB1.Save
   WB2.Save
   WB3.Save
   Application.Quit

Application.DisplayAlerts = True
Application.ScreenUpdating = True
    End Sub
</code>```

答:
Thanks for the suggestion @Peter_Pesch , the resolution is as follows [PS. I have 4 files open at the time when VBA is running]:</p>

```<code>   ....

   WB1.Save
   WB1.Saved = True
   WB2.Saved = True
   WB3.Saved = True
   ActiveWorkbook.Saved = True
   Application.Quit

Application.DisplayAlerts = True
Application.ScreenUpdating = True
    End Sub
</code>```

Body:
In general the problem I have is that whenever my code comes to an end (see below) it:

Asks whether or not to save changes to .csv
When I click "Yes", it opens the window with location of the file, where I have to select "Save"

Asks whether or not to overwrite the file

Asks whether or not to maintain CSV format

Can you advise how can I remove above prompts [simultaneously having this file saved/overwriting the old version]?

Sub Test()
Application.ScreenUpdating = False
Application.DisplayAlerts = False

****rest of the code***

   WB1.Save
   WB2.Save
   WB3.Save
   Application.Quit

Application.DisplayAlerts = True
Application.ScreenUpdating = True
    End Sub

Body:
Thanks for the suggestion @Peter_Pesch , the resolution is as follows [PS. I have 4 files open at the time when VBA is running]:

   ....

   WB1.Save
   WB1.Saved = True
   WB2.Saved = True
   WB3.Saved = True
   ActiveWorkbook.Saved = True
   Application.Quit

Application.DisplayAlerts = True
Application.ScreenUpdating = True
    End Sub


问:
Boost Asio tcp::acceptor access violation exception
I'm trying to create a tcp::acceptor and a libtorrent::session side by side, but I get an access violation exception when waiting for input from std::cin. The access violation occurs in the Boost IOCP implementation as shown by the stack trace.

Windows 8.1

MSVC 12.0 (Visual Studio 2013)

boost v1.57.0

libtorrent-rasterbar v1.0.3

A minimal example which lets me reproduce the issue,

```<code>#include <boost/asio.hpp>
#include <libtorrent/session.hpp>

int main(int argc, char *argv[])
{
    boost::asio::io_service io_service;
    boost::asio::ip::tcp::acceptor acceptor(io_service);

    libtorrent::session s;

    std::string line;
    std::getline(std::cin, line); // <----- trigger

    return 0;
}
</code>```

The stack trace is

```<code>lt_test.exe!boost::asio::detail::win_iocp_socket_service_base::do_open(boost::asio::detail::win_iocp_socket_service_base::base_implementation_type & impl, int family, int type, int protocol, boost::system::error_code & ec) Line 300   C++
lt_test.exe!boost::asio::detail::win_iocp_socket_service<boost::asio::ip::tcp>::open(boost::asio::detail::win_iocp_socket_service<boost::asio::ip::tcp>::implementation_type & impl, const boost::asio::ip::tcp & protocol, boost::system::error_code & ec) Line 192  C++
lt_test.exe!boost::asio::socket_acceptor_service<boost::asio::ip::tcp>::open(boost::asio::detail::win_iocp_socket_service<boost::asio::ip::tcp>::implementation_type & impl, const boost::asio::ip::tcp & protocol, boost::system::error_code & ec) Line 144  C++
lt_test.exe!boost::asio::basic_socket_acceptor<boost::asio::ip::tcp,boost::asio::socket_acceptor_service<boost::asio::ip::tcp> >::open(const boost::asio::ip::tcp & protocol, boost::system::error_code & ec) Line 310    C++
lt_test.exe!libtorrent::aux::session_impl::setup_listener(libtorrent::listen_socket_t * s, boost::asio::ip::basic_endpoint<boost::asio::ip::tcp> ep, int & retries, bool v6_only, int flags, boost::system::error_code & ec) Line 2089    C++
lt_test.exe!libtorrent::aux::session_impl::open_listen_port(int flags, boost::system::error_code & ec) Line 2243  C++
lt_test.exe!libtorrent::aux::session_impl::init() Line 1258   C++
lt_test.exe!libtorrent::aux::session_impl::main_thread() Line 4880    C++
lt_test.exe!boost::_mfi::mf0<void,libtorrent::aux::session_impl>::operator()(libtorrent::aux::session_impl * p) Line 50   C++
lt_test.exe!boost::_bi::list1<boost::_bi::value<libtorrent::aux::session_impl *> >::operator()<boost::_mfi::mf0<void,libtorrent::aux::session_impl>,boost::_bi::list0>(boost::_bi::type<void> __formal, boost::_mfi::mf0<void,libtorrent::aux::session_impl> & f, boost::_bi::list0 & a, int __formal) Line 254   C++
lt_test.exe!boost::_bi::bind_t<void,boost::_mfi::mf0<void,libtorrent::aux::session_impl>,boost::_bi::list1<boost::_bi::value<libtorrent::aux::session_impl *> > >::operator()() Line 21   C++
lt_test.exe!boost::asio::detail::win_thread::func<boost::_bi::bind_t<void,boost::_mfi::mf0<void,libtorrent::aux::session_impl>,boost::_bi::list1<boost::_bi::value<libtorrent::aux::session_impl *> > > >::run() Line 117 C++
lt_test.exe!boost::asio::detail::win_thread_function(void * arg) Line 118 C++
[External Code]
[Frames below may be incorrect and/or missing, no symbols loaded for kernel32.dll]
</code>```

Removing the acceptor makes the access violation exception disappear.

What causes this?

答: I ran into the same problem. I was helped by adding BOOST_ASIO_ENABLE_CANCELIO in preprocessor definitions. Here you can find more information.

Body:
I'm trying to create a tcp::acceptor and a libtorrent::session side by side, but I get an access violation exception when waiting for input from std::cin. The access violation occurs in the Boost IOCP implementation as shown by the stack trace.

Windows 8.1

MSVC 12.0 (Visual Studio 2013)

boost v1.57.0

libtorrent-rasterbar v1.0.3

A minimal example which lets me reproduce the issue,

#include <boost/asio.hpp>
#include <libtorrent/session.hpp>

int main(int argc, char *argv[])
{
    boost::asio::io_service io_service;
    boost::asio::ip::tcp::acceptor acceptor(io_service);

    libtorrent::session s;

    std::string line;
    std::getline(std::cin, line); // <----- trigger

    return 0;
}

The stack trace is

lt_test.exe!boost::asio::detail::win_iocp_socket_service_base::do_open(boost::asio::detail::win_iocp_socket_service_base::base_implementation_type & impl, int family, int type, int protocol, boost::system::error_code & ec) Line 300   C++
lt_test.exe!boost::asio::detail::win_iocp_socket_service<boost::asio::ip::tcp>::open(boost::asio::detail::win_iocp_socket_service<boost::asio::ip::tcp>::implementation_type & impl, const boost::asio::ip::tcp & protocol, boost::system::error_code & ec) Line 192  C++
lt_test.exe!boost::asio::socket_acceptor_service<boost::asio::ip::tcp>::open(boost::asio::detail::win_iocp_socket_service<boost::asio::ip::tcp>::implementation_type & impl, const boost::asio::ip::tcp & protocol, boost::system::error_code & ec) Line 144  C++
lt_test.exe!boost::asio::basic_socket_acceptor<boost::asio::ip::tcp,boost::asio::socket_acceptor_service<boost::asio::ip::tcp> >::open(const boost::asio::ip::tcp & protocol, boost::system::error_code & ec) Line 310    C++
lt_test.exe!libtorrent::aux::session_impl::setup_listener(libtorrent::listen_socket_t * s, boost::asio::ip::basic_endpoint<boost::asio::ip::tcp> ep, int & retries, bool v6_only, int flags, boost::system::error_code & ec) Line 2089    C++
lt_test.exe!libtorrent::aux::session_impl::open_listen_port(int flags, boost::system::error_code & ec) Line 2243  C++
lt_test.exe!libtorrent::aux::session_impl::init() Line 1258   C++
lt_test.exe!libtorrent::aux::session_impl::main_thread() Line 4880    C++
lt_test.exe!boost::_mfi::mf0<void,libtorrent::aux::session_impl>::operator()(libtorrent::aux::session_impl * p) Line 50   C++
lt_test.exe!boost::_bi::list1<boost::_bi::value<libtorrent::aux::session_impl *> >::operator()<boost::_mfi::mf0<void,libtorrent::aux::session_impl>,boost::_bi::list0>(boost::_bi::type<void> __formal, boost::_mfi::mf0<void,libtorrent::aux::session_impl> & f, boost::_bi::list0 & a, int __formal) Line 254   C++
lt_test.exe!boost::_bi::bind_t<void,boost::_mfi::mf0<void,libtorrent::aux::session_impl>,boost::_bi::list1<boost::_bi::value<libtorrent::aux::session_impl *> > >::operator()() Line 21   C++
lt_test.exe!boost::asio::detail::win_thread::func<boost::_bi::bind_t<void,boost::_mfi::mf0<void,libtorrent::aux::session_impl>,boost::_bi::list1<boost::_bi::value<libtorrent::aux::session_impl *> > > >::run() Line 117 C++
lt_test.exe!boost::asio::detail::win_thread_function(void * arg) Line 118 C++
[External Code]
[Frames below may be incorrect and/or missing, no symbols loaded for kernel32.dll]

Removing the acceptor makes the access violation exception disappear.

What causes this?


问:
How we can Convert large size of decimal values to float and without exponential values
When I try to convert values from decimal to float, they are shown with exponential values

When I converted numeric to decimal values then they show with .00 fractional,
but I required only in numeric.

check blow mention query.

```<code>select  cast(CAST(435468867990778789.89 as decimal(35, 2))as float) as APPARENTWACTIMP
select  CAST(43546886799090787 as decimal(35, 2))as APPARENTWACTIMP
select  CAST(43546886799090787 as decimal(35, 2))as APPARENTWACTIMP
select CAST(43546886799090787.89 as float)
</code>```

Above Query result are

```<code>4.35468867990779E+17
43546886799090787.00
43546886799090787.00
4.35468867990908E+16
</code>```

But I require a result like "435468867990778789.89".

答:
Try this</p>

```<code>select try_parse('43546886799090787.89' as numeric(35,2) using 'en-US')
</code>```

Body:
When I try to convert values from decimal to float, they are shown with exponential values

When I converted numeric to decimal values then they show with .00 fractional,
but I required only in numeric.

check blow mention query.

select  cast(CAST(435468867990778789.89 as decimal(35, 2))as float) as APPARENTWACTIMP
select  CAST(43546886799090787 as decimal(35, 2))as APPARENTWACTIMP
select  CAST(43546886799090787 as decimal(35, 2))as APPARENTWACTIMP
select CAST(43546886799090787.89 as float)

Above Query result are

4.35468867990779E+17
43546886799090787.00
43546886799090787.00
4.35468867990908E+16

But I require a result like "435468867990778789.89".

Body:
Try this

select try_parse('43546886799090787.89' as numeric(35,2) using 'en-US')


问:
Mapping OpenCMS structured content XML field to a SOLR field
We are trying to map an OpenCMS structured content XML field to a SOLR field in order to perform a search using that field as a filter.

The XML field is described this way in the XSD file:

```<code><xsd:complexType name="OpenCmsContrato">
    <xsd:sequence>
    [...]
        <xsd:element name="numeroExpediente" type="OpenCmsString" minOccurs="1" maxOccurs="1" />
    [...]
    </xsd:sequence>
    <xsd:attribute name="language" type="OpenCmsLocale" use="required"/>
</xsd:complexType>
</code>```

And these are the search settings for the element, defined in the same XSD file:

```<code><xsd:annotation>
    <xsd:appinfo>
    [...]
        <searchsettings>
            <searchsetting element="numeroExpediente" searchcontent="true">
                <solrfield targetfield="numexp" />
            </searchsetting>
        </searchsettings>
    [...]
    </xsd:appinfo>
</xsd:annotation>
</code>```

The target SOLR field "numexp" is defined this way in SOLR's schema.xml file:

```<code><fields>
    <field name="numexp"                 type="string"       indexed="true"  stored="true" />
    [...]
</fields>
</code>```

And this is the way we perform the query to SOLR on a JSP file:

```<code>CmsSearchManager manager = OpenCms.getSearchManager();
CmsSolrIndex index = manager.getIndexSolr("Solr Online");

String query = "fq=type:contrato";

if (!"".equals(text))
    query += "&fq=numexp:" + text;

CmsSolrResultList listFiles = index.search(cmso, query);
</code>```

When we execute this code, we get listFiles.size() = 0, but when we change the filter field to the predifined SOLR field "content", this way:

```<code>if (!"".equals(text))
    query += "&fq=content:" + text;
</code>```

we get the expected result.

With the CmsSearchResource object we get using the "content" SOLR field as filter, we are able to iterate over the fields of its inner I_CmsSearchDocument, getting this list as result:

```<code>id
contentblob
path
type
suffix
created
lastmodified
contentdate
relased
expired
res_locales
con_locales
template_prop
default-file_prop
notification-interval_prop
NavPos_prop
enable-notification_prop
locale_prop
NavText_prop
Title_prop
category
ca_excerpt
timestamp
score
link
</code>```

No presence of the "numexp" field on the list. Why?
Are we missing any step? Do we have to configure something else in order to make the mapping work?

答:
We had the same problem. The thing is SOLR will not index nested contents by itself, you have to say whether or not the field should be indexed or not.

For Instance, lets say we have a Event XSD, containing Information concerning the Event and the Company:

```<code><xsd:complexType name="OpenCmsEvent">
    <xsd:sequence>
        <xsd:element name="EventInformation" type="OpenCmsEventInformation" minOccurs="1" maxOccurs="1" />
        <xsd:element name="EventHost" type="OpenCmsEventHost" minOccurs="0" maxOccurs="1" />
    </xsd:sequence>
    <xsd:attribute name="language" type="OpenCmsLocale" use="required" />
</xsd:complexType>
</code>```

We want to know the links to the companys from Eventhost

```<code><xsd:complexType name="OpenCmsEventHost">
    <xsd:sequence>
        <xsd:element name="company" type="OpenCmsVfsFile" minOccurs="1" maxOccurs="unbounded" />
    </xsd:sequence>
    <xsd:attribute name="language" type="OpenCmsLocale" use="optional" />
</xsd:complexType>
</code>```

The following mapping will give us the Informatione we want

```<code><searchsettings>
    <searchsetting element="EventHost/company" searchcontent="true">
            <solrfield targetfield="companyurl"/>
    </searchsetting>
</searchsettings>
</code>```

When doing this on existing ressources, dont forget to reindex your solar index!

Body:
We are trying to map an OpenCMS structured content XML field to a SOLR field in order to perform a search using that field as a filter.

The XML field is described this way in the XSD file:

<xsd:complexType name="OpenCmsContrato">
    <xsd:sequence>
    [...]
        <xsd:element name="numeroExpediente" type="OpenCmsString" minOccurs="1" maxOccurs="1" />
    [...]
    </xsd:sequence>
    <xsd:attribute name="language" type="OpenCmsLocale" use="required"/>
</xsd:complexType>

And these are the search settings for the element, defined in the same XSD file:

<xsd:annotation>
    <xsd:appinfo>
    [...]
        <searchsettings>
            <searchsetting element="numeroExpediente" searchcontent="true">
                <solrfield targetfield="numexp" />
            </searchsetting>
        </searchsettings>
    [...]
    </xsd:appinfo>
</xsd:annotation>

The target SOLR field "numexp" is defined this way in SOLR's schema.xml file:

<fields>
    <field name="numexp"                 type="string"       indexed="true"  stored="true" />
    [...]
</fields>

And this is the way we perform the query to SOLR on a JSP file:

CmsSearchManager manager = OpenCms.getSearchManager();
CmsSolrIndex index = manager.getIndexSolr("Solr Online");

String query = "fq=type:contrato";

if (!"".equals(text))
    query += "&fq=numexp:" + text;

CmsSolrResultList listFiles = index.search(cmso, query);

When we execute this code, we get listFiles.size() = 0, but when we change the filter field to the predifined SOLR field "content", this way:

if (!"".equals(text))
    query += "&fq=content:" + text;

we get the expected result.

With the CmsSearchResource object we get using the "content" SOLR field as filter, we are able to iterate over the fields of its inner I_CmsSearchDocument, getting this list as result:

id
contentblob
path
type
suffix
created
lastmodified
contentdate
relased
expired
res_locales
con_locales
template_prop
default-file_prop
notification-interval_prop
NavPos_prop
enable-notification_prop
locale_prop
NavText_prop
Title_prop
category
ca_excerpt
timestamp
score
link

No presence of the "numexp" field on the list. Why?
Are we missing any step? Do we have to configure something else in order to make the mapping work?

Body:
We had the same problem. The thing is SOLR will not index nested contents by itself, you have to say whether or not the field should be indexed or not.

For Instance, lets say we have a Event XSD, containing Information concerning the Event and the Company:

<xsd:complexType name="OpenCmsEvent">
    <xsd:sequence>
        <xsd:element name="EventInformation" type="OpenCmsEventInformation" minOccurs="1" maxOccurs="1" />
        <xsd:element name="EventHost" type="OpenCmsEventHost" minOccurs="0" maxOccurs="1" />
    </xsd:sequence>
    <xsd:attribute name="language" type="OpenCmsLocale" use="required" />
</xsd:complexType>

We want to know the links to the companys from Eventhost

<xsd:complexType name="OpenCmsEventHost">
    <xsd:sequence>
        <xsd:element name="company" type="OpenCmsVfsFile" minOccurs="1" maxOccurs="unbounded" />
    </xsd:sequence>
    <xsd:attribute name="language" type="OpenCmsLocale" use="optional" />
</xsd:complexType>

The following mapping will give us the Informatione we want

<searchsettings>
    <searchsetting element="EventHost/company" searchcontent="true">
            <solrfield targetfield="companyurl"/>
    </searchsetting>
</searchsettings>

When doing this on existing ressources, dont forget to reindex your solar index!


问:
Why will a scheduled tasklet from an interrupt handler not run
I have an interrupt handler which schedules a tasklet as follows (pseudo code) -

```<code>struct tasklet_struct mytasklet;

void my_tasklet_function(unsigned long arg1) {
    ...
    pr_alert("Inside tasklet function\n");
    ...
}

int my_probe() {
    ....
    ....
    tasklet_init(&mytasklet, my_tasklet_function, arg1);
    ....
    /* Register interrupt handler my_irq_handler*/
    ....
}

irqreturn_t my_irq_handler(int irq, void *data) {
    ...
    status = read_reg(base_addr, intr_status_reg_offset)
    write_reg(base_addr, intr_status_reg_offset, status);

    if (status & INTR_MASK_1) {
         ....
         pr_alert("intr 1 came\n");
    }
    ...
    ...
    pr_alert("Schedule tasklet\n");
    tasklet_schedule(&mytasklet);
    pr_alert("Exit irq\n");

    return IRQ_HANDLED;
}
</code>```

It is observed that the kernel hangs after the following prints

```<code>intr 1 came
Schedule tasklet
</code>```

The "Exit irq" print never shows up. The prints in the tasklet function are not printed.

What can be the reason for this tasklet not getting scheduled?

What can possibly cause the kernel to hang?

答:
tasklet scheduling should NOT be done in IRQ handler.
You can check the schedule_tasklet() code in lxr.
In the IRQ handler, calling schedule_tasklet() only set the bit for the softirq, and link your tasklet.

When irq_exit() is called, it will check if it is still in interrupt context (nested interrupt). If not, and there is any tasklet enabled, it will call the softirq handlers, which in turn will call tasklet.

Body:
I have an interrupt handler which schedules a tasklet as follows (pseudo code) -

struct tasklet_struct mytasklet;

void my_tasklet_function(unsigned long arg1) {
    ...
    pr_alert("Inside tasklet function\n");
    ...
}

int my_probe() {
    ....
    ....
    tasklet_init(&mytasklet, my_tasklet_function, arg1);
    ....
    /* Register interrupt handler my_irq_handler*/
    ....
}

irqreturn_t my_irq_handler(int irq, void *data) {
    ...
    status = read_reg(base_addr, intr_status_reg_offset)
    write_reg(base_addr, intr_status_reg_offset, status);

    if (status & INTR_MASK_1) {
         ....
         pr_alert("intr 1 came\n");
    }
    ...
    ...
    pr_alert("Schedule tasklet\n");
    tasklet_schedule(&mytasklet);
    pr_alert("Exit irq\n");

    return IRQ_HANDLED;
}

It is observed that the kernel hangs after the following prints

intr 1 came
Schedule tasklet

The "Exit irq" print never shows up. The prints in the tasklet function are not printed.

What can be the reason for this tasklet not getting scheduled?

What can possibly cause the kernel to hang?


问:
Regex PCRE matching on an URL with multiple parameters random values
Sample GET request I want to match on with regex PCRE:

random.php?blue=value1&green=value2&red=value3&orange=value4&grey=value5&black=value6

Facts:

random.php - The filename is random, only the ".php?" is fixed

I have about 10 colors defined as parameters

No specific order to the colors - .php?blue=[a-zA-Z0-9]{1,20}

Can be just 2 colors as parameters, or all the 10, but I want to match on all GET requests, multiple parameters are joined with \&

Values are always between 1-20 and with alphanumerical - .php?blue=[a-zA-Z0-9]{1,20}

How would you approach this?

答:
Perhaps something like:

```<code>[^\s/?]+\.php\?((?:blue|orange|red|black)=[a-zA-Z0-9]{1,20})(?:&(?1)){1,9}(?:$|#.*)
</code>```

(complete with the colours you want)

(?1) is a reference to the first capture group subpattern.

I added a support for an eventual anchor part #.*. Feel free to remove it if you don't need or want it.

Body:
Perhaps something like:

[^\s/?]+\.php\?((?:blue|orange|red|black)=[a-zA-Z0-9]{1,20})(?:&(?1)){1,9}(?:$|#.*)

(complete with the colours you want)

(?1) is a reference to the first capture group subpattern.

I added a support for an eventual anchor part #.*. Feel free to remove it if you don't need or want it.


问:
Android Debugging with Logcat and Emulator. Is it possible?
This is pretty simple: I'm using NetBeans on Linux with Android emulator 1.6. I have Logcat on my android phone, but the process of getting the messages to somewhere readable isn't smooth at all.

Can someone tell me how to get Logcat running on the emulator? Is there anything I can do to see debug messages other then having to copy the apk to my phone and testing it?

Thanks in advance!

答:
If you have setup nbandroid you can find the adb logcat viewer in netbeans under:
Window -> Output -> ADB Log

--edit
Just followed up on the post above and started using C:\Program Files (x86)\Android\android-sdk-windows\tools\ddms which is alot better then the one in netbeans.


问:
How to handle image file download across multiple timezone?
I'm downloading an image file from a server, everyday after 9am in morning as per my Timezone. I also wish to display the file next day sharp at 9am

So I'll update that image file before 9am as per my Timezone, that'll make sure I get updated image file everyday. And all users get enough time to download that same image file i.e 23hrs and 45 minutes max.
* 15 mins are considered for updation purpose

Now the app works fine if users are from my Timezone, but it won't work if user are ahead then my Timezone. Chances are more of getting same image file twice.

Also if I choose to update file as per Timezone where 9am occurs first then users in other part won't get 23hrs and 45 mintues time to download.

I'd like to know any other solution rather than having seperate server for each timezone, as it is also difficult to implement in app too.

UPDATE
I think there is no way to provide a window of 23hrs and 45 mins max and displaying image next day at 9am. Both things can't be achieved in multiple timezones.

I'm using an image with hotlink i.e direct download link with same address.

答: You can do this via using UTC time. You need to get current UTC and then convert the time to device current time zone then you will be able to get what you want. Hope that helps.</p>


问:
How do I exit a WPF application programmatically?
How is one supposed to exit an application such as when the user clicks on the Exit menu item from the File menu?

I have tried:

```<code>this.Dispose();
this.Exit();
Application.ShutDown();
Application.Exit();
Application.Dispose();
</code>```

Among many others. Nothing works.

答:
Another way you can do this:

```<code>System.Diagnostics.Process.GetCurrentProcess().Kill();
</code>```

This will force kill your application. It always works, even in a multi-threaded application.

Note: Just be careful not to lose unsaved data in another thread.

ContentLicense: CC BY-SA 4.0

Body:
How is one supposed to exit an application such as when the user clicks on the Exit menu item from the File menu?

I have tried:

this.Dispose();
this.Exit();
Application.ShutDown();
Application.Exit();
Application.Dispose();

Among many others. Nothing works.

Body:
Another way you can do this:

System.Diagnostics.Process.GetCurrentProcess().Kill();

This will force kill your application. It always works, even in a multi-threaded application.

Note: Just be careful not to lose unsaved data in another thread.


问:
Ajax JSON for each
Hello guys i  had a simple ajax request this also is working fine, but i had to loop trought the data and display all 10 names in the object allready searched it in stack but the object which i had is a bit to complicated. any suggestions how i can solve it?</p>

```<code>$( document ).ready(function() {
$.ajax({
   url: 'XXXXXXX',
   data: {
      format: 'json'
   },
   error: function() {
   alert('ERROR');
   },
   sasdataType: 'json',
   success: function(data) {
    /*var $hotelname = $('<h1>').text(data.result.hotel[0].displayname);
        $('#hotel-name').append($hotelname)*/
    console.log(data);
   },
   type: 'GET'
});
});
</code>```

答:
$(document).ready(function() {
  $.ajax({
    url: 'XXX',
    data: {
      format: 'json'
    },
    error: function() {
      alert('ERROR');
    },
    sasdataType: 'json',
    success: function(data) {
      $.each(data.result.hotel, function(index, value) {
        $('#hotel-name').append($('
').text(value.displayname));
      });
    },
    type: 'GET'
  });
});```
<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='hotel-name'></div></code>```

You cane directly loop through hotel to get the hotel names as below using $.each

```<code>$.each(data.result.hotel, function(index, value) {
  console.log(value.displayname);
});
</code>```

Title: Ajax JSON for each

Body:
Hello guys i  had a simple ajax request this also is working fine, but i had to loop trought the data and display all 10 names in the object allready searched it in stack but the object which i had is a bit to complicated. any suggestions how i can solve it?

$( document ).ready(function() {
$.ajax({
   url: 'XXXXXXX',
   data: {
      format: 'json'
   },
   error: function() {
   alert('ERROR');
   },
   sasdataType: 'json',
   success: function(data) {
    /*var $hotelname = $('
').text(data.result.hotel[0].displayname);
        $('#hotel-name').append($hotelname)*/
    console.log(data);
   },
   type: 'GET'
});
});

Body:
$(document).ready(function() {
  $.ajax({
    url: 'XXX',
    data: {
      format: 'json'
    },
    error: function() {
      alert('ERROR');
    },
    sasdataType: 'json',
    success: function(data) {
      $.each(data.result.hotel, function(index, value) {
        $('#hotel-name').append($('<h1>').text(value.displayname));
      });
    },
    type: 'GET'
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='hotel-name'></div>

You cane directly loop through hotel to get the hotel names as below using $.each

$.each(data.result.hotel, function(index, value) {
  console.log(value.displayname);
});


问:
AVA: setup different timeout for each test case
I writing asynchronous tests using AVA, and need to setup custom timeout for each test cases. I've not found out any information about this possibility and my tests seems like this:

import test from 'ava';

test.cb('super test', t => {
    setTimeout(() => {
        t.is(1, 1);
        t.end();
    }, 10000);

    setTimeout(() => {
        t.fail("Timeout error!");
        t.end();
    }, 100);
});```

Does anybody know another way to implement this in AVA?

答:
I don't know if AVA has something like this built in. I suspect not, as it seems like quite an unusual use-case.

But you could create a utility function that implements some kind of a "timeout test":

```<code>import test from 'ava';

function timeout (ms, fn) {
   return function (t) {
       setTimeout(() => {
           t.fail("Timeout error!")
           t.end()
       }, ms)
       fn(t)
   }
}

test.cb('super test', timeout(10000, t => {
    t.is(1, 1);
}));
</code>```

Body:
I writing asynchronous tests using AVA, and need to setup custom timeout for each test cases. I've not found out any information about this possibility and my tests seems like this:

import test from 'ava';

test.cb('super test', t => {
    setTimeout(() => {
        t.is(1, 1);
        t.end();
    }, 10000);

    setTimeout(() => {
        t.fail("Timeout error!");
        t.end();
    }, 100);
});

Does anybody know another way to implement this in AVA?

Body:
I don't know if AVA has something like this built in. I suspect not, as it seems like quite an unusual use-case.

But you could create a utility function that implements some kind of a "timeout test":

import test from 'ava';

function timeout (ms, fn) {
   return function (t) {
       setTimeout(() => {
           t.fail("Timeout error!")
           t.end()
       }, ms)
       fn(t)
   }
}

test.cb('super test', timeout(10000, t => {
    t.is(1, 1);
}));


问:
The currently selected JAXB library provider is invalid
I'm using Elipse Neon with JDK 1.8 and run time environment GlassFish 4.1. I have tried to add to my project facet configuration JAXB 2.2 however I'm getting the error: The currently selected JAXB library provider is invalid.

What I can do, or what library I should use in order to use JAXB configuration. Additionally I mention that I'm using JAXB for a JAX-RS project with Jersey implementation (natively build into Glassfish)

Regards,

答: JAX-RS supports the automatic creation of XML and JSON via JAXB. You are NOT require to explicitly add any jars as part of JAXB configuration.


问:
Detect if a ScrollView is scrolling up or down - Android
I have one ScrollView with one LinearLayout with TextViews. I want to detect when ScrollView is scrolling up or down to hide/show ActionBar.

答:
A sure short answer

```<code>scroll.setOnScrollChangeListener(new View.OnScrollChangeListener() {
    @Override
    public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                int x = scrollY - oldScrollY;
                if (x > 0) {
                    //scroll up
                } else if (x < 0) {
                    //scroll down
                } else {

                }

    }
});
</code>```

Body:
A sure short answer

scroll.setOnScrollChangeListener(new View.OnScrollChangeListener() {
    @Override
    public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                int x = scrollY - oldScrollY;
                if (x > 0) {
                    //scroll up
                } else if (x < 0) {
                    //scroll down
                } else {

                }

    }
});


问:
Which syntax highlighter does Firefox Quantum Dev Tools use?
Does anyone know what kind of syntax highlighter (and what theme, if it has any) does Firefox Quantum (v57+) use in it's Inspector panel of their developer tools?

I believe it was introduced with their new Photon UI, but I'm not sure whether it's just an updated code coloring theme or a totally new coloring processor.

Their blog article:
https://hacks.mozilla.org/2017/09/developer-edition-devtools-update-now-with-photon-ui/

答:
As far as I know, the general tree view within the Firefox DevTools Inspector is developed by Mozilla. Though the editor used when editing a node (context menu > Edit As HTML) is CodeMirror, which is also used in other parts of the DevTools like the Debugger.

The theme is self-created to fit to the Photon layout.


问:
Java Scanner unable to read file
I'm doing a very simple text-parsing program, using files given to me by a friend.
However, when I open the file using a Scanner like so,

```<code>Scanner scan = new Scanner(new File(path));
System.err.println(scan.hasNext());
while(scan.hasNextLine())
    System.err.println(scan.nextLine());
System.err.println(scan.next());
</code>```

result:

```<code>false
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:855)
at java.util.Scanner.next(Scanner.java:1364)
at Test.main(Test.java:18)
</code>```

the scanner treats the file(which is some 1400 lines long) as empty.

Can anyone think of any reason a scanner might not be able to see a file? I suspect the fact that the file was imported from a Windows machine to a Linux machine may have something to do with it, but my mind is open to other possibilities

edited for formatting and code errors

答:
EDIT: Fisrt guess was wrong

The file might have 1400 lines full of whitespaces.

Title: Java Scanner unable to read file

Body:
I'm doing a very simple text-parsing program, using files given to me by a friend.
However, when I open the file using a Scanner like so,

Scanner scan = new Scanner(new File(path));
System.err.println(scan.hasNext());
while(scan.hasNextLine())
    System.err.println(scan.nextLine());
System.err.println(scan.next());

result:

false
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:855)
at java.util.Scanner.next(Scanner.java:1364)
at Test.main(Test.java:18)

the scanner treats the file(which is some 1400 lines long) as empty.

Can anyone think of any reason a scanner might not be able to see a file? I suspect the fact that the file was imported from a Windows machine to a Linux machine may have something to do with it, but my mind is open to other possibilities

edited for formatting and code errors


问:
Parallel or Event driven functions in Python?
I'm fairly new to Python, so maybe my whole concept of how this should Work is wrong:

I'm building a RFID Reader for time managing purposes. E.g. User logs in with RFID chip -> Timer Starts counting and updating a Google  spreadsheet every Minute. The updating part works fine, but takes a little while. But I want to Check for RFID Logins all the time. Somewhere  I read that Event driven Programming is what I'm looking for.

Currently I'm doing everything in a while true loop, which feels like a hack itself. Can i somehow just execute my code when the RFID reader sends a signal? And then time my update to run every minute or so parallel? I'd like to know whats best practice here.

答:
Parallel and Event Driven are basically orthogonal, although it is generally "easy" to parallelize events. I'll first cover the event driven and then the parallelisation, although you may only want to use the later.

The "normal" controlflow in python is iterative.
That means you define the instructions the code should do and then the pc executes these step for step.
There are different ways to organize your code (functional, event driven, object oriented, although I don't want to say that these are absolute categories where you can only do X or Y). Event driven normally means you define events and how to handle them.
There is nothing you could program with event driven which you couldn't program iterativly and vice versa.

Python mainly got support for asyncronuos stuff with version 3.4 when the asyncio library was introduced.
With 3.5 you also got syntactic sugar await and async. Because you are on 2.7 this is not available for you.
There is a backport from asyncio named trollius but this is overkill if you only have a "low amount of events". Also it's not hard to "roll your own basic event loop" (of course asyncio and trollius do much more, but if we are not going to use these features, why bother?).

The basic workflow is waiting for events and then handling them as they occur:

```<code>events = []

while waiting_for_events:
    if events:
        event = events.pop()
        handle_event(event)
</code>```

You somehow need to know how to differentiate between events and how to handle them.
For a "full featured event loop" you would probably use different classes with inheritance, but lets just use a name for each event.
Also we probably need some kind of data like which RFID we encountered.

```<code>from collections import namedtuple
Event = namedtuple("Event", ["name", "data"])
</code>```

Then we simply need to map events to how to handle them:

```<code>def handle_rfid(data):
    ...

def handle_timer(data):
    ...

event_handler_mapping = {"rfid": handle_rfid, "timer": handle_timer}

def handle_event(event):
    event_handler_mapping[event.name](event.data)
</code>```

We still need to generate events, so lets rewrite the eventloop to get events:

```<code>timer = 0
current_time = time.perf_counter()

while waiting_for_events:

    rfid = get_rfids()
    if rfid:
        events.append(Event("rfid", rfid))

    if timer > 1:
        events.append(Event("timer", timer))
        timer = 0
    else:
        timer += time.perf_counter() - current_time
        current_time = time.perf_counter()

    if events:
        event = events.pop()
        handle_event(event)
</code>```

And now we are "event driven". The nice thing is that we can easily extend this to more events.
The bad thing is that it still does the same thing you probably already have, but it's more complicated.
Also if the event handling needs a lot of time (which seems to be the case with updating the spreadsheet) the other events will not
be generated and handled. This is were parallelism comes into play.

Parallelism basically means we can use multiple cores.
Here we actually only need "concurrency" which means two things can happen at once.
This is "easier" than true parallelism, we can just switch between different things but still do all the things sequentially.
In python this basically boils down to multiprocessing (parallelism) and threads ("only" concurrency) (in other programming languages threads actually do parallelism, but in python this is for reasons I don't want to go into not the case).
The problem with concurrency is always syncronisation. If things can happen at the same time, bad things can happen
if two threads try to change the same variable. In general as long as you only use thread-safe functions to access variables shared between threads, you are safe.

In python threads are created by the threading module.
I personally find it hard to understand if you don't already know threads from somewhere else, but the gist is the following:
To run a function in a thread use threading.Thread(target=function) and then thread.start().
You could use it the following:

```<code>def run_in_thread(f, *args, **kwargs):
    thread = Thread(target=f, args=args, kwargs=kwargs)
    thread.start()

def _update_spreadsheet(data):
    # logic here

# when using the event driven approach from above
def handle_timer(data):
    run_in_thread(_update_spreadsheet(data))
</code>```

Note that if you access variables from within _update_spreadsheet you need to be carefule to only use thread safe function.
It is "best" to use as little inter-thread communication as possible.
A queue is often a good choice.

You can use parallelism/concurrency without the event driven organisation.
Because we already divided the code into event handlers we can call long running event handlers in a seperate thread.

If we have lots of events and event handlers running everything in threads is a bad idea (because thread switching has an overhead).
Thus asyncio (and probably all other event loops) implement some kind of "wait until atleast one event can be handled".
This is most interesting for internet input and output, because these need "a long time".
Often something like select is used.
Other events (timers, read from disk, wait for some hardware events, ...) need other mechanisms for "wake me up when something happens". Integrating all of these is one of the features asyncio offer for you.

Body:
Parallel and Event Driven are basically orthogonal, although it is generally "easy" to parallelize events. I'll first cover the event driven and then the parallelisation, although you may only want to use the later.

The "normal" controlflow in python is iterative.
That means you define the instructions the code should do and then the pc executes these step for step.
There are different ways to organize your code (functional, event driven, object oriented, although I don't want to say that these are absolute categories where you can only do X or Y). Event driven normally means you define events and how to handle them.
There is nothing you could program with event driven which you couldn't program iterativly and vice versa.

Python mainly got support for asyncronuos stuff with version 3.4 when the asyncio library was introduced.
With 3.5 you also got syntactic sugar await and async. Because you are on 2.7 this is not available for you.
There is a backport from asyncio named trollius but this is overkill if you only have a "low amount of events". Also it's not hard to "roll your own basic event loop" (of course asyncio and trollius do much more, but if we are not going to use these features, why bother?).

The basic workflow is waiting for events and then handling them as they occur:

events = []

while waiting_for_events:
    if events:
        event = events.pop()
        handle_event(event)

You somehow need to know how to differentiate between events and how to handle them.
For a "full featured event loop" you would probably use different classes with inheritance, but lets just use a name for each event.
Also we probably need some kind of data like which RFID we encountered.

from collections import namedtuple
Event = namedtuple("Event", ["name", "data"])

Then we simply need to map events to how to handle them:

def handle_rfid(data):
    ...

def handle_timer(data):
    ...

event_handler_mapping = {"rfid": handle_rfid, "timer": handle_timer}

def handle_event(event):
    event_handler_mapping[event.name](event.data)

We still need to generate events, so lets rewrite the eventloop to get events:

timer = 0
current_time = time.perf_counter()

while waiting_for_events:

    rfid = get_rfids()
    if rfid:
        events.append(Event("rfid", rfid))

    if timer > 1:
        events.append(Event("timer", timer))
        timer = 0
    else:
        timer += time.perf_counter() - current_time
        current_time = time.perf_counter()

    if events:
        event = events.pop()
        handle_event(event)

And now we are "event driven". The nice thing is that we can easily extend this to more events.
The bad thing is that it still does the same thing you probably already have, but it's more complicated.
Also if the event handling needs a lot of time (which seems to be the case with updating the spreadsheet) the other events will not
be generated and handled. This is were parallelism comes into play.

Parallelism basically means we can use multiple cores.
Here we actually only need "concurrency" which means two things can happen at once.
This is "easier" than true parallelism, we can just switch between different things but still do all the things sequentially.
In python this basically boils down to multiprocessing (parallelism) and threads ("only" concurrency) (in other programming languages threads actually do parallelism, but in python this is for reasons I don't want to go into not the case).
The problem with concurrency is always syncronisation. If things can happen at the same time, bad things can happen
if two threads try to change the same variable. In general as long as you only use thread-safe functions to access variables shared between threads, you are safe.

In python threads are created by the threading module.
I personally find it hard to understand if you don't already know threads from somewhere else, but the gist is the following:
To run a function in a thread use threading.Thread(target=function) and then thread.start().
You could use it the following:

def run_in_thread(f, *args, **kwargs):
    thread = Thread(target=f, args=args, kwargs=kwargs)
    thread.start()

def _update_spreadsheet(data):
    # logic here

# when using the event driven approach from above
def handle_timer(data):
    run_in_thread(_update_spreadsheet(data))

Note that if you access variables from within _update_spreadsheet you need to be carefule to only use thread safe function.
It is "best" to use as little inter-thread communication as possible.
A queue is often a good choice.

You can use parallelism/concurrency without the event driven organisation.
Because we already divided the code into event handlers we can call long running event handlers in a seperate thread.

If we have lots of events and event handlers running everything in threads is a bad idea (because thread switching has an overhead).
Thus asyncio (and probably all other event loops) implement some kind of "wait until atleast one event can be handled".
This is most interesting for internet input and output, because these need "a long time".
Often something like select is used.
Other events (timers, read from disk, wait for some hardware events, ...) need other mechanisms for "wake me up when something happens". Integrating all of these is one of the features asyncio offer for you.


问:
POST fetch request - converting to JSON

I'm trying to make a post request from a react front-end to a php file.

```<code>handleFormSubmit(event) {
  event.preventDefault()
  let payload = this.state.email;
  fetch(`http://website.com/file.php`, {
    credentials: 'same-origin',
    method: 'POST',
    mode: 'cors',
    headers:{
      'Access-Control-Allow-Origin':'*'
      },
    body: payload
  })
  .then((response) => response.json() )
  .then((body) => {
    console.log(body);
    this.setState({
      email: body,
      message: 'Success!'
    });
  });
}
</code>```

I am getting an error message instead of having the fetch request go through.

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '...' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

答:
Looks like your server does not include the Access-Control-Allow-Origin header in response to a preflight request (OPTIONS). A CORS request will fail if Access-Control-Allow-Origin is missing.

Here are some great articles that explain how CORS works:

https://www.html5rocks.com/en/tutorials/cors/

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Hope this helps!

Title: POST fetch request - converting to JSON

Body:
I'm trying to make a post request from a react front-end to a php file.

handleFormSubmit(event) {
  event.preventDefault()
  let payload = this.state.email;
  fetch(`http://website.com/file.php`, {
    credentials: 'same-origin',
    method: 'POST',
    mode: 'cors',
    headers:{
      'Access-Control-Allow-Origin':'*'
      },
    body: payload
  })
  .then((response) => response.json() )
  .then((body) => {
    console.log(body);
    this.setState({
      email: body,
      message: 'Success!'
    });
  });
}

I am getting an error message instead of having the fetch request go through.

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '...' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.


问:
Angular takes Array as object and does not display the values
// Updated along the discussion

I try to get JSON objects(Tasks) via http request and parse them into my own class to display them on my HTML page(Task Overwiew).

This is what I get:

This is the json array my php returns:

```<code>    {"result":[{"id":"3","znumber":"vor21423"},{"id":"2","znumber":"vor213"}]}
</code>```

Here's my last try from the turtorial on angular.io. I've tested many answers but most of them relate to .json() which is no longer part of the HTML client.

```<code>export class ApiComponent {
 private apiUrl = 'http://localhost:81/work/get.php';

 results: Steve[];

 constructor(private http: HttpClient) {
 }

 ngOnInit() {
   this.getSteves();
 }

 getSteves() {
   this.http.get<ItemsResponse>(this.apiUrl)
      .subscribe(data => {
        this.results = data.result
          .map(steve => new Steve(steve.id, steve.zNumber));
            console.log(this.results);
            console.log(data);
      });
  }
}
</code>```

The Interface

```<code>import { Steve } from './Steve';
export interface ItemsResponse {
  results: Steve[];
}
</code>```

HTML

```<code><div>
  <div *ngFor="let steve of results">
    <p> - {{steve.id}}</p>
    <p> - {{steve.zNumber}}</p>
  </div>
</div>
</code>```

The Steve Class

```<code>export class Steve {
  public id = 0;
  public zNumber = '';

  constructor(id: number, zNumber: string) {
    this.id = id;
    this.zNumber = zNumber;
  }
}
</code>```

The API

```<code><?php
require_once('db.php');

$sql = 'SELECT * FROM jobs ORDER BY id DESC';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    $data = array();
    while($row = $result->fetch_assoc()){
        $data[] = $row;
    }
    echo json_encode(array('result' => $data));
} else {
    echo 0;
}
?>
</code>```

答:
First, you are not receiving an array, but an Object, so you need to get the array from the object result. Secondly, if you want to make the objects in the array instances of Steve, you need to explicitly tell Angular so.

You ItemsResponse actually looks like this (notice the result instead of results):

```<code>import { Steve } from './Steve';

export interface ItemsResponse {
  result: Steve[];
}
</code>```

The request should show that you are getting response of type ItemsResponse.

```<code> getSteves() {
   this.http.get<ItemsResponse>(this.apiUrl)
     .subscribe(data => {
       // your array is in 'result' object of your response
       this.results = data.result
         // create instances of your class
         .map(steve => new Steve(steve.id, steve.znumber))
     });
  }
</code>```

Body:
// Updated along the discussion

I try to get JSON objects(Tasks) via http request and parse them into my own class to display them on my HTML page(Task Overwiew).

This is what I get:

This is the json array my php returns:

    {"result":[{"id":"3","znumber":"vor21423"},{"id":"2","znumber":"vor213"}]}

Here's my last try from the turtorial on angular.io. I've tested many answers but most of them relate to .json() which is no longer part of the HTML client.

export class ApiComponent {
 private apiUrl = 'http://localhost:81/work/get.php';

 results: Steve[];

 constructor(private http: HttpClient) {
 }

 ngOnInit() {
   this.getSteves();
 }

 getSteves() {
   this.http.get<ItemsResponse>(this.apiUrl)
      .subscribe(data => {
        this.results = data.result
          .map(steve => new Steve(steve.id, steve.zNumber));
            console.log(this.results);
            console.log(data);
      });
  }
}

The Interface

import { Steve } from './Steve';
export interface ItemsResponse {
  results: Steve[];
}

HTML

 - {{steve.id}}

 - {{steve.zNumber}}

The Steve Class

export class Steve {
  public id = 0;
  public zNumber = '';

  constructor(id: number, zNumber: string) {
    this.id = id;
    this.zNumber = zNumber;
  }
}

The API

<?php
require_once('db.php');

$sql = 'SELECT * FROM jobs ORDER BY id DESC';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    $data = array();
    while($row = $result->fetch_assoc()){
        $data[] = $row;
    }
    echo json_encode(array('result' => $data));
} else {
    echo 0;
}
?>

Body:
First, you are not receiving an array, but an Object, so you need to get the array from the object result. Secondly, if you want to make the objects in the array instances of Steve, you need to explicitly tell Angular so.

You ItemsResponse actually looks like this (notice the result instead of results):

import { Steve } from './Steve';

export interface ItemsResponse {
  result: Steve[];
}

The request should show that you are getting response of type ItemsResponse.

 getSteves() {
   this.http.get<ItemsResponse>(this.apiUrl)
     .subscribe(data => {
       // your array is in 'result' object of your response
       this.results = data.result
         // create instances of your class
         .map(steve => new Steve(steve.id, steve.znumber))
     });
  }


问:
Connect phpMyAdmin docker image to the HOST MySQL server listening only on 127.0.0.1
I am looking to connect a PhpMyAdmin running in a container (Docker) to a MySQL server running on the host and listening on 127.0.0.1.

However, when I give docker the varuable -e PMA_HOST=127.0.0.1, it only look on it's own Docker network... How would I be able to talk to my host MySQL DB server ?

答:
You shouldn't use 127.0.0.1 as IP address to refer to the host as that will point to the docker container where phpAdmin is running.

You need to find the IP address of the host on the docker0 interface as use that ip instead. You can do that using:

```<code>-e PMA_HOST=$(ip route show | grep docker0 | awk '{print $9}')
</code>```

Body:
You shouldn't use 127.0.0.1 as IP address to refer to the host as that will point to the docker container where phpAdmin is running.

You need to find the IP address of the host on the docker0 interface as use that ip instead. You can do that using:

-e PMA_HOST=$(ip route show | grep docker0 | awk '{print $9}')


答:
hope this is helpful for you

$.ajax({
   url: 'https://www.hrs.de/hotel/service/mmsuggest-group?query=k%C3%B6ln&language=de',
   data: {
      format: 'json'
   },
   error: function() {
   alert('ERROR');
   },
   sasdataType: 'json',
   success: function(data) {
    /*var $hotelname = $('
').text(data.result.hotel[0].displayname);
        $('#hotel-name').append($hotelname)*/
    console.log(data);
  console.log(data.result);
data.result.hotel.forEach(function(hd){console.log(hd.displayname)});
   },
   type: 'GET'
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script></code>```

Title: Ajax JSON for each

Body:
hope this is helpful for you

$.ajax({
   url: 'https://www.hrs.de/hotel/service/mmsuggest-group?query=k%C3%B6ln&language=de',
   data: {
      format: 'json'
   },
   error: function() {
   alert('ERROR');
   },
   sasdataType: 'json',
   success: function(data) {
    /*var $hotelname = $('<h1>').text(data.result.hotel[0].displayname);
        $('#hotel-name').append($hotelname)*/
    console.log(data);
  console.log(data.result);
data.result.hotel.forEach(function(hd){console.log(hd.displayname)});
   },
   type: 'GET'
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>


问:
Return a Specific Revision of An Object
I want to get my Envers to return the entities with the highest revision that is still below a given revision number.

What I came up with is the following:

```<code>@PersistenceContext
private EntityManager em;

@Test
public void test() throws Exception {
    final Number before = AuditReaderFactory.get(this.em).getRevisionNumberForDate(new Date(Long.MAX_VALUE));

    final UserEntity user = new UserEntity().loginName("one");
    doInTransaction(() -> this.em.persist(user));

    final Number middle = AuditReaderFactory.get(this.em).getRevisionNumberForDate(new Date(Long.MAX_VALUE));

    user.setLoginName("two");
    doInTransaction(() -> this.em.persist(user));

    final Number after = AuditReaderFactory.get(this.em).getRevisionNumberForDate(new Date(Long.MAX_VALUE));

    Assert.assertEquals(new ArrayList<>(), getRevisions(before));
    Assert.assertEquals(Arrays.asList(user), getRevisions(middle));
    Assert.assertEquals(new ArrayList<>(), getRevisions(after));
}

private void doInTransaction(Runnable magic) {
    try {
        this.em.getTransaction().begin();
        magic.run();
        this.em.getTransaction().commit();
    } catch (final Exception e) {
        this.em.getTransaction().rollback();
        throw new RuntimeException(e);
    }
}

private List<UserEntity> getRevisions(Number revisionNumber) {
    final AuditReader auditReader = AuditReaderFactory.get(this.em);
    try {
        return auditReader.createQuery().forRevisionsOfEntity(UserEntity.class, true, false)
                .add(AuditEntity.revisionNumber().maximize().computeAggregationInInstanceContext()) // the highest revision possible
                .add(AuditEntity.revisionNumber().le(revisionNumber)) // as long as the revision is below or equal to revisionNumber
                .getResultList();
    } catch (final NoResultException e) {
        return null;
    }
}
</code>```

The method that does not work is getRevisions(Object, Number). It returns nothing for the before revision (that's correct), it returns still nothing for the middle revision (not correct, now the entity exists!) and then returns something for the after revision (also not correct, the entity was deleted).

The reason for that behavior is clear when we look at the resulting SQL:

```<code>SELECT * from user_aud u
    WHERE u.REV = (
        SELECT MAX (v.REV)
            FROM user_aud v
            WHERE v.id=u.id
        )
    AND u.REV <= ? ORDER BY u.REV asc
</code>```

The u.REV <= ? part should be inside the inner query. The way it's generated now Hibernate decides that the max revision is 3, and then selects nothing because rev should be below 2.

I can't seem to figure out how to fix the query, and there is very little documentation on the subject. I tried removing computeAggregationInInstanceCont(), but there was no change in how the code behaved.

What is the correct query to get the highest revision below a user-defined value?

答:
You should be able to acquire the highest revision number below a specified value as follows:

```<code>AuditReaderFactory.get( session )
  .createQuery()
  .forRevisionsOfEntity( EntityClass.class, true, true )
  .addOrder( AuditEntity.revisionNumber().desc() )
  .add( AuditEntity.id().eq( entityId ) )
  .add( AuditEntity.revisionNumber().le( userSuppliedValue ) )
  .setMaxResults( 1 )
  .singleResult();
</code>```

This will order all revisions in descending order and returns the first entry.  The rows in the result set will be for EntityClass entity with primary key entityId and applies the restriction that the the entities had to be audited with a revision number less-than or equal-to the supplied value.

Title: Return a Specific Revision of An Object

Body:
I want to get my Envers to return the entities with the highest revision that is still below a given revision number.

What I came up with is the following:

@PersistenceContext
private EntityManager em;

@Test
public void test() throws Exception {
    final Number before = AuditReaderFactory.get(this.em).getRevisionNumberForDate(new Date(Long.MAX_VALUE));

    final UserEntity user = new UserEntity().loginName("one");
    doInTransaction(() -> this.em.persist(user));

    final Number middle = AuditReaderFactory.get(this.em).getRevisionNumberForDate(new Date(Long.MAX_VALUE));

    user.setLoginName("two");
    doInTransaction(() -> this.em.persist(user));

    final Number after = AuditReaderFactory.get(this.em).getRevisionNumberForDate(new Date(Long.MAX_VALUE));

    Assert.assertEquals(new ArrayList<>(), getRevisions(before));
    Assert.assertEquals(Arrays.asList(user), getRevisions(middle));
    Assert.assertEquals(new ArrayList<>(), getRevisions(after));
}

private void doInTransaction(Runnable magic) {
    try {
        this.em.getTransaction().begin();
        magic.run();
        this.em.getTransaction().commit();
    } catch (final Exception e) {
        this.em.getTransaction().rollback();
        throw new RuntimeException(e);
    }
}

private List<UserEntity> getRevisions(Number revisionNumber) {
    final AuditReader auditReader = AuditReaderFactory.get(this.em);
    try {
        return auditReader.createQuery().forRevisionsOfEntity(UserEntity.class, true, false)
                .add(AuditEntity.revisionNumber().maximize().computeAggregationInInstanceContext()) // the highest revision possible
                .add(AuditEntity.revisionNumber().le(revisionNumber)) // as long as the revision is below or equal to revisionNumber
                .getResultList();
    } catch (final NoResultException e) {
        return null;
    }
}

The method that does not work is getRevisions(Object, Number). It returns nothing for the before revision (that's correct), it returns still nothing for the middle revision (not correct, now the entity exists!) and then returns something for the after revision (also not correct, the entity was deleted).

The reason for that behavior is clear when we look at the resulting SQL:

SELECT * from user_aud u
    WHERE u.REV = (
        SELECT MAX (v.REV)
            FROM user_aud v
            WHERE v.id=u.id
        )
    AND u.REV <= ? ORDER BY u.REV asc

The u.REV <= ? part should be inside the inner query. The way it's generated now Hibernate decides that the max revision is 3, and then selects nothing because rev should be below 2.

I can't seem to figure out how to fix the query, and there is very little documentation on the subject. I tried removing computeAggregationInInstanceCont(), but there was no change in how the code behaved.

What is the correct query to get the highest revision below a user-defined value?

Body:
You should be able to acquire the highest revision number below a specified value as follows:

AuditReaderFactory.get( session )
  .createQuery()
  .forRevisionsOfEntity( EntityClass.class, true, true )
  .addOrder( AuditEntity.revisionNumber().desc() )
  .add( AuditEntity.id().eq( entityId ) )
  .add( AuditEntity.revisionNumber().le( userSuppliedValue ) )
  .setMaxResults( 1 )
  .singleResult();

This will order all revisions in descending order and returns the first entry.  The rows in the result set will be for EntityClass entity with primary key entityId and applies the restriction that the the entities had to be audited with a revision number less-than or equal-to the supplied value.


问:
SQL 2 HAVING syntax
My professor is teaching sql 2, and used an statement like the code below into a query:

```<code>HAVING SUM(column) > subselect
</code>```

Where subselect is something like SELECT AVG(column) FROM ...

This subselect returns only one value, but I could not understand how is it possible to compare a function (the sum) with a subselect. The subselect should return a table, right? Then how is it possible to compare a table with a value? That did not make sense to me.

Thanks in advance.

答:
In principle you are right, if you look at it in a relational way.
But SQL is an industry standard and allows the abbreviation of comparing a scalar value with a result table with only a single row and column.

Depending on the exact implementation, it even allows to compare a scalar with a list of values (a column with more than one value), although you actually should write ... value > ALL (subselect), it is often accepted without the ALL keyword.

This is both valid syntax in the where and in the having clause

Title: SQL 2 HAVING syntax

Body:
My professor is teaching sql 2, and used an statement like the code below into a query:

HAVING SUM(column) > subselect

Where subselect is something like SELECT AVG(column) FROM ...

This subselect returns only one value, but I could not understand how is it possible to compare a function (the sum) with a subselect. The subselect should return a table, right? Then how is it possible to compare a table with a value? That did not make sense to me.

Thanks in advance.


问:
The app's Info.plist must contain an NSMotionUsageDescription key
I am getting the following error during the runtime:

This app has crashed because it attempted to access privacy-sensitive data without a usage description.  The app's Info.plist must contain an NSMotionUsageDescription key with a string value explaining to the user how the app uses this data.

I have added the key to the plist file:

```<code><!--  Motion -->
<key>NSMotionUsageDescription</key>
<string>This app needs to be able to access your motion use</string>
</code>```

and this the code in AppDelegate:

```<code>if ([CMMotionActivityManager isActivityAvailable])
{
    CMMotionActivityManager *motionManager = [[CMMotionActivityManager alloc] init];
    NSOperationQueue *motionActivityQueue = [[NSOperationQueue alloc] init];

    [motionManager queryActivityStartingFromDate:[NSDate distantPast] toDate:[NSDate date] toQueue:motionActivityQueue withHandler:^(NSArray *activities, NSError *error) {
        if (error && (error.domain == CMErrorDomain) && (error.code == CMErrorMotionActivityNotAuthorized)) {

        } else if (activities || !error) {

        }

        dispatch_async(dispatch_get_main_queue(), ^{

        });
    }];
}
</code>```

Why am I keep getting this crash? I deleted all the derived folder, cleaned the project. But still asking me the key! Is it an Apple bug?

答: I found the problem. I hope one day it will help someone. Go to Project Settings -> Info -> Under the Custom iOS Target Properties section find the Required background modes and add your key here as well. I don't know why not all my plist file keys are here.</p>

Body:
I am getting the following error during the runtime:

This app has crashed because it attempted to access privacy-sensitive data without a usage description.  The app's Info.plist must contain an NSMotionUsageDescription key with a string value explaining to the user how the app uses this data.

I have added the key to the plist file:

<key>NSMotionUsageDescription</key>
<string>This app needs to be able to access your motion use</string>

and this the code in AppDelegate:

if ([CMMotionActivityManager isActivityAvailable])
{
    CMMotionActivityManager *motionManager = [[CMMotionActivityManager alloc] init];
    NSOperationQueue *motionActivityQueue = [[NSOperationQueue alloc] init];

    [motionManager queryActivityStartingFromDate:[NSDate distantPast] toDate:[NSDate date] toQueue:motionActivityQueue withHandler:^(NSArray *activities, NSError *error) {
        if (error && (error.domain == CMErrorDomain) && (error.code == CMErrorMotionActivityNotAuthorized)) {

        } else if (activities || !error) {

        }

        dispatch_async(dispatch_get_main_queue(), ^{

        });
    }];
}

Why am I keep getting this crash? I deleted all the derived folder, cleaned the project. But still asking me the key! Is it an Apple bug?


问:
Clueless about this error: wrong sign in 'by' argument
I have the following dataset:

```<code> >k1[1:10,]
       id  web_name first_name second_name   position     date team1 team2 game_week points home_away team_scored team_conceded minutes goals assists
    1   1 Fabianski     Lukasz   Fabianski Goalkeeper 17/08/13   ARS   AVL         1      0         H           1             3       0     0       0
    2   1 Fabianski     Lukasz   Fabianski Goalkeeper 24/08/13   ARS   FUL         2      0         A           3             1       0     0       0
    3   1 Fabianski     Lukasz   Fabianski Goalkeeper 01/09/13   ARS   TOT         3      0         H           1             0       0     0       0
    4   1 Fabianski     Lukasz   Fabianski Goalkeeper 14/09/13   ARS   SUN         4      0         A           3             1       0     0       0
    5   1 Fabianski     Lukasz   Fabianski Goalkeeper 22/09/13   ARS   STK         5      0         H           3             1       0     0       0
    6   1 Fabianski     Lukasz   Fabianski Goalkeeper 28/09/13   ARS   SWA         6      0         A           2             1       0     0       0
    7   1 Fabianski     Lukasz   Fabianski Goalkeeper 06/10/13   ARS   WBA         7      0         A           1             1       0     0       0
    8   1 Fabianski     Lukasz   Fabianski Goalkeeper 19/10/13   ARS   NOR         8      0         H           4             1       0     0       0
    9   1 Fabianski     Lukasz   Fabianski Goalkeeper 26/10/13   ARS   CRY         9      0         A           2             0       0     0       0
    10  1 Fabianski     Lukasz   Fabianski Goalkeeper 02/11/13   ARS   LIV        10      0         H           2             0       0     0       0
</code>```

When I run the code:

```<code> > k2<- as.data.frame(k1 %>% group_by(id) %>%
 mutate(min1 = lag(minutes, default=NA)) %>%
 mutate(min3 = rollapply(min1,width=3,mean, align= "right", fill=NA)))
</code>```

I receive the error:

```<code>Error: wrong sign in 'by' argument
</code>```

However grouping by team1 via this code just works fine:

```<code>> k2<- as.data.frame(k1 %>% group_by(team1) %>%
   mutate(min1 = lag(minutes, default=NA)) %>%
   mutate(min3 = rollapply(min1,width=3,mean, align= "right", fill=NA)))
</code>```

Pretty clueless why this is happening. Any help is appreciated.

答:
It can have different reasons, But simply it can happen if you pass a NULL dataframe to rollapply function

Also consider the using of zoo() as

```<code>rollapply(Zoo(min1),width=3,mean, align= "right", fill=NA)
</code>```

Body:
I have the following dataset:

 >k1[1:10,]
       id  web_name first_name second_name   position     date team1 team2 game_week points home_away team_scored team_conceded minutes goals assists
    1   1 Fabianski     Lukasz   Fabianski Goalkeeper 17/08/13   ARS   AVL         1      0         H           1             3       0     0       0
    2   1 Fabianski     Lukasz   Fabianski Goalkeeper 24/08/13   ARS   FUL         2      0         A           3             1       0     0       0
    3   1 Fabianski     Lukasz   Fabianski Goalkeeper 01/09/13   ARS   TOT         3      0         H           1             0       0     0       0
    4   1 Fabianski     Lukasz   Fabianski Goalkeeper 14/09/13   ARS   SUN         4      0         A           3             1       0     0       0
    5   1 Fabianski     Lukasz   Fabianski Goalkeeper 22/09/13   ARS   STK         5      0         H           3             1       0     0       0
    6   1 Fabianski     Lukasz   Fabianski Goalkeeper 28/09/13   ARS   SWA         6      0         A           2             1       0     0       0
    7   1 Fabianski     Lukasz   Fabianski Goalkeeper 06/10/13   ARS   WBA         7      0         A           1             1       0     0       0
    8   1 Fabianski     Lukasz   Fabianski Goalkeeper 19/10/13   ARS   NOR         8      0         H           4             1       0     0       0
    9   1 Fabianski     Lukasz   Fabianski Goalkeeper 26/10/13   ARS   CRY         9      0         A           2             0       0     0       0
    10  1 Fabianski     Lukasz   Fabianski Goalkeeper 02/11/13   ARS   LIV        10      0         H           2             0       0     0       0

When I run the code:

 > k2<- as.data.frame(k1 %>% group_by(id) %>%
 mutate(min1 = lag(minutes, default=NA)) %>%
 mutate(min3 = rollapply(min1,width=3,mean, align= "right", fill=NA)))

I receive the error:

Error: wrong sign in 'by' argument

However grouping by team1 via this code just works fine:

> k2<- as.data.frame(k1 %>% group_by(team1) %>%
   mutate(min1 = lag(minutes, default=NA)) %>%
   mutate(min3 = rollapply(min1,width=3,mean, align= "right", fill=NA)))

Pretty clueless why this is happening. Any help is appreciated.

Body:
It can have different reasons, But simply it can happen if you pass a NULL dataframe to rollapply function

Also consider the using of zoo() as

rollapply(Zoo(min1),width=3,mean, align= "right", fill=NA)


问:
Radio livestream does not play on android webview but plays on the browser
I have a number of radio live stream embedded on a website. They are playing on the website but not on android web-view. I am not sure what i am missing in my code. Please help. Below is the code i am using:</p>

```<code>   webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setAppCacheEnabled(true);
    swipe.setRefreshing(true);
    webView.loadUrl(getString(url));

    webView.getSettings().setPluginState(WebSettings.PluginState.ON);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setAllowContentAccess(true);
    webView.getSettings().supportZoom();
    webView.getSettings().setBuiltInZoomControls(true);

    webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    webView.setSoundEffectsEnabled(true);
</code>```

答:
```<code>    try using this it is working on my code

WebView mWebView;
     mWebView = (WebView)findViewById(R.id.webView);

        // Enable Javascript
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        // Force links and redirects to open in the WebView instead of in a browser
        mWebView.setWebChromeClient(new WebChromeClient() {
                @Override
                public void onExceededDatabaseQuota(String url, String databaseIdentifier,
                                                    long currentQuota, long estimatedSize, long totalUsedQuota,
                                                    WebStorage.QuotaUpdater quotaUpdater) {
                    // try to keep quota size as big as possible else database will not get created in HTML 5 app
                    quotaUpdater.updateQuota(estimatedSize * 2);
                }
            });

            webViewRoi.setWebChromeClient(new WebChromeClient());
   mWebView.loadUrl("url");
</code>```

Body:
I have a number of radio live stream embedded on a website. They are playing on the website but not on android web-view. I am not sure what i am missing in my code. Please help. Below is the code i am using:

   webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setAppCacheEnabled(true);
    swipe.setRefreshing(true);
    webView.loadUrl(getString(url));

    webView.getSettings().setPluginState(WebSettings.PluginState.ON);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setAllowContentAccess(true);
    webView.getSettings().supportZoom();
    webView.getSettings().setBuiltInZoomControls(true);

    webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    webView.setSoundEffectsEnabled(true);


问:
DocType is not showing in the rendered output from JSF
I am trying into integrate JSF1.2, Richfaces 3.3.0 GA, Facelets1.1 and JQuery. The issue i am facing is the rendered output is starting from  i.e its missing the Doc type and HTML Tag.

For example

```<code>   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"><ui:composition>
<head>  </head> <body>  kkkkkkkkkkkkkkkkk   </body> </ui:composition></html>
</code>```

and the rendered output is

```<code><head> <script src="/wmat/a4j/g/3_3_0.GA/org/ajax4jsf/framework.pack.js.faces" type="text/javascript"></script><script src="/wmat/a4j/g/3_3_0.GA/org/richfaces/ui.pack.js.faces" type="text/javascript"></script><link class="component" href="/wmat/a4j/s/3_3_0.GAorg/richfaces/renderkit/html/css/basic_both.xcss/DATB/eAFrvajdHLp8hjQAEgwDtA__.faces" rel="stylesheet" type="text/css" /><link class="component" href="/wmat/a4j/s/3_3_0.GAorg/richfaces/renderkit/html/css/extended_both.xcss/DATB/eAFrvajdHLp8hjQAEgwDtA__.faces" media="rich-extended-skinning" rel="stylesheet" type="text/css" /><link class="component" href="/wmat/a4j/s/3_3_0.GA/org/richfaces/skin.xcss/DATB/eAFrvajdHLp8hjQAEgwDtA__.faces" rel="stylesheet" type="text/css" /><script type="text/javascript">window.RICH_FACES_EXTENDED_SKINNING_ON=true;</script></head> <body> kkkkkkkkkkkkkkkkk</body></html>
</code>```

I dont know why its not showing the <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 Tags in the rendered output.

Jquery Components are not working because of this issue.

Can anybody please help me to sort it out? Not sure what I am missing in this

In the ice face forum i can see the same issue reported but iceface provides a direct solution for this. Please check this link for more details

Thanks in Advance

Jobin

答: Get rid of those <ui:composition> tags, they do not belong in the "master template". They belong in the include template files. When used in include files, only their content will be parsed and everything outside those tags will be ignored, which is what you're now seeing.

Body:
I am trying into integrate JSF1.2, Richfaces 3.3.0 GA, Facelets1.1 and JQuery. The issue i am facing is the rendered output is starting from  i.e its missing the Doc type and HTML Tag.

For example

   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <ui:composition>
     kkkkkkkkkkkkkkkkk    </ui:composition>

and the rendered output is

 <link class="component" href="/wmat/a4j/s/3_3_0.GAorg/richfaces/renderkit/html/css/basic_both.xcss/DATB/eAFrvajdHLp8hjQAEgwDtA__.faces" rel="stylesheet" type="text/css" /><link class="component" href="/wmat/a4j/s/3_3_0.GAorg/richfaces/renderkit/html/css/extended_both.xcss/DATB/eAFrvajdHLp8hjQAEgwDtA__.faces" media="rich-extended-skinning" rel="stylesheet" type="text/css" /><link class="component" href="/wmat/a4j/s/3_3_0.GA/org/richfaces/skin.xcss/DATB/eAFrvajdHLp8hjQAEgwDtA__.faces" rel="stylesheet" type="text/css" />  kkkkkkkkkkkkkkkkk

I dont know why its not showing the <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 Tags in the rendered output.

Jquery Components are not working because of this issue.

Can anybody please help me to sort it out? Not sure what I am missing in this

In the ice face forum i can see the same issue reported but iceface provides a direct solution for this. Please check this link for more details

Thanks in Advance

Jobin


问:
How to know whether the triangle is valid or not by angles?
I want to write a c++ program that finds whether the triangle is valid or not
 here's my code:

```<code>#include <iostream>
using namespace std;
int main () {
    int a,b,c;
    cin>>a>>b>>c;
    if (a+b+c==180)
    cout <<"Yes";
    else
    cout <<"No";
    return 0;
}
</code>```

The user will enter 3 angles e.g 50 30 100 it will print valid Yes, but what if he enters

0 0 180 it will print yes by entering only one angle. that isn't triangle and my program will print yes. What should I do to fix this?

答:
In a sense, you are right; there is no point in continuing the program if you have enough information to determine that the triangle is invalid. So, in the code snippet I propose below, you can see that once the user enters a value < 0 or > 180, the program terminates with a suitable error message. Similarly, once the running sum exceeds 180, the program also terminates early.

Finally once all three values are input for the angles, all of which independently are valid angles of a triangle, their sum is checked.

```<code>int main()
{
    // assuming angles must be integers:
    int angle, sum = 0;
    for (int i = 0; i < 3; i++) {
        cin >> angle;
        if (angle <= 0 || angle >= 180) {
            cout << "Error: Angle must be between 0 and 180\n";
            return 0;
        }

        sum += angle;

        if (sum > 180) {
            cout << "Error: angles too large\n";
            return 0;
        }
    }

    if (sum == 180) {
        cout << "Valid Triangle!\n";
    } else {
        cout << "Error: angles must add up to 180\n";
    }
    return 0;
}
</code>```

Body:
I want to write a c++ program that finds whether the triangle is valid or not
 here's my code:

#include <iostream>
using namespace std;
int main () {
    int a,b,c;
    cin>>a>>b>>c;
    if (a+b+c==180)
    cout <<"Yes";
    else
    cout <<"No";
    return 0;
}

The user will enter 3 angles e.g 50 30 100 it will print valid Yes, but what if he enters

0 0 180 it will print yes by entering only one angle. that isn't triangle and my program will print yes. What should I do to fix this?

Body:
In a sense, you are right; there is no point in continuing the program if you have enough information to determine that the triangle is invalid. So, in the code snippet I propose below, you can see that once the user enters a value < 0 or > 180, the program terminates with a suitable error message. Similarly, once the running sum exceeds 180, the program also terminates early.

Finally once all three values are input for the angles, all of which independently are valid angles of a triangle, their sum is checked.

int main()
{
    // assuming angles must be integers:
    int angle, sum = 0;
    for (int i = 0; i < 3; i++) {
        cin >> angle;
        if (angle <= 0 || angle >= 180) {
            cout << "Error: Angle must be between 0 and 180\n";
            return 0;
        }

        sum += angle;

        if (sum > 180) {
            cout << "Error: angles too large\n";
            return 0;
        }
    }

    if (sum == 180) {
        cout << "Valid Triangle!\n";
    } else {
        cout << "Error: angles must add up to 180\n";
    }
    return 0;
}


问:
Array value overwrites instead of retaining old value - Javascript
This is what I want.

User enters a numerical input. If he enters 2, the code prompts to enter two player names.

The player names are stored in an array. There is a 'next' button in the page, when user clicks it, the code prompts to enter another two names.

The next is the tricky part: Right now there are four names entered on two separate sessions. Now I need a nested array should hold the usernames in separate arrays based on the session.

I've tried many codes but only the following at least comes closer.
But what happens is, every time user enters a new list of usernames, a new array is created but previous arrays are also over written.

var TotalNumOfPlayers = prompt("Enter The Total Number Of Players! (For example 2)");
var nameOfPlayers = [];
var loopThroughAllNames = new Array(new Array());
var NextList = document.querySelector("#NextList");
var tempArr = [];

addValue();

function addValue() {
  for (var i = 0; i < TotalNumOfPlayers; i++) {
    tempArr[i] = prompt("Enter Player name "+(i+1));
  }

  loopThroughAllNames.push(tempArr);
}

NextList.addEventListener("click", function() {
  addValue();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="NextList">Next list</button></code>```

答:
Your for-loop always starts from 0 for the same tempArr (initialized once outside the addValue method), hence it overwrites the previous entries.

```<code>for (var i = 0; i < TotalNumOfPlayers; i++) {
    tempArr[i] = prompt("Enter Player name "+(i+1));
  }
</code>```

You need to initialize the tempArr array inside the addValue method.

Demo

var loopThroughAllNames = [];
var TotalNumOfPlayers = prompt("Enter The Total Number Of Players!");
addValue();

function addValue ()
{
  var tempArr = [];
  for (var i = 0; i < TotalNumOfPlayers; i++) {
    tempArr[i] = prompt("Enter Player name");
  }
  loopThroughAllNames.push(tempArr);
  console.log( loopThroughAllNames );
}

var NextList = document.querySelector("#NextList");
NextList.addEventListener("click", function() {
  addValue( );
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="NextList">Next list</button></code>```

Body:
This is what I want.

User enters a numerical input. If he enters 2, the code prompts to enter two player names.

The player names are stored in an array. There is a 'next' button in the page, when user clicks it, the code prompts to enter another two names.

The next is the tricky part: Right now there are four names entered on two separate sessions. Now I need a nested array should hold the usernames in separate arrays based on the session.

I've tried many codes but only the following at least comes closer.
But what happens is, every time user enters a new list of usernames, a new array is created but previous arrays are also over written.

var TotalNumOfPlayers = prompt("Enter The Total Number Of Players! (For example 2)");
var nameOfPlayers = [];
var loopThroughAllNames = new Array(new Array());
var NextList = document.querySelector("#NextList");
var tempArr = [];

addValue();

function addValue() {
  for (var i = 0; i < TotalNumOfPlayers; i++) {
    tempArr[i] = prompt("Enter Player name "+(i+1));
  }

  loopThroughAllNames.push(tempArr);
}

NextList.addEventListener("click", function() {
  addValue();

});

<button id="NextList">Next list</button>

Body:
Your for-loop always starts from 0 for the same tempArr (initialized once outside the addValue method), hence it overwrites the previous entries.

for (var i = 0; i < TotalNumOfPlayers; i++) {
    tempArr[i] = prompt("Enter Player name "+(i+1));
  }

You need to initialize the tempArr array inside the addValue method.

Demo

var loopThroughAllNames = [];
var TotalNumOfPlayers = prompt("Enter The Total Number Of Players!");
addValue();

function addValue ()
{
  var tempArr = [];
  for (var i = 0; i < TotalNumOfPlayers; i++) {
    tempArr[i] = prompt("Enter Player name");
  }
  loopThroughAllNames.push(tempArr);
  console.log( loopThroughAllNames );
}

var NextList = document.querySelector("#NextList");
NextList.addEventListener("click", function() {
  addValue( );
});

<button id="NextList">Next list</button>