问:
Handling Local vs Remote Database TimeZone Differences in Tests
I have unit test in Java that writes a constant Timestamp to a row in my local test database, reads it back and compares it to what I expected. This works fine on my local laptop which is under the GMT timezone.

When I commit the code to our continuous integration server, the test fails with the different in time being -5 hours. This is no surprise since our integration server is hosted on AWS on the East Coast of US. However, it is causing a problem...

Short of changing my local MySQL server to have the same timezone as the remote server (and having all the developers in my team do so also), can anyone show me how to fix this issue in code without getting too hacky?

```<code>//Fetch actual table contents
IDataSet databaseDataSet = databaseTester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("batch");

// Load expected data from an XML dataset
IDataSet expectedDataSet = new XmlDataSet(getClass().getResourceAsStream("/dbunit/expected_insert_batch.xml"));
ITable expectedTable = expectedDataSet.getTable("batch");

// Assert actual database table match expected table
Assertion.assertEquals(expectedTable, actualTable);
</code>```

Thanks,

答: I suggest you make all your systems use the same time zone e.g. UTC/GMT+0 and only use the timezone when displaying to a user or in reporting.</p>

Body:
I have unit test in Java that writes a constant Timestamp to a row in my local test database, reads it back and compares it to what I expected. This works fine on my local laptop which is under the GMT timezone.

When I commit the code to our continuous integration server, the test fails with the different in time being -5 hours. This is no surprise since our integration server is hosted on AWS on the East Coast of US. However, it is causing a problem...

Short of changing my local MySQL server to have the same timezone as the remote server (and having all the developers in my team do so also), can anyone show me how to fix this issue in code without getting too hacky?

//Fetch actual table contents
IDataSet databaseDataSet = databaseTester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("batch");

// Load expected data from an XML dataset
IDataSet expectedDataSet = new XmlDataSet(getClass().getResourceAsStream("/dbunit/expected_insert_batch.xml"));
ITable expectedTable = expectedDataSet.getTable("batch");

// Assert actual database table match expected table
Assertion.assertEquals(expectedTable, actualTable);

Thanks,


来源: stackexchange

问:
Python How do I count the number of month of 30 days after a date
I have a dataframe containing date, and I would like to process the data as follow for feature engineering

df

```<code>date
2016/1/1
2015/2/10
2016/4/5
</code>```

after process I would like to make the df looks like

```<code>date      Jan    Feb   Mar   Apr
2016/1/1  30     0    0      0    //date from 1/1 to 1/30 : the number of dates in jan
2015/2/10  0     19   11     0    //date from 2/10 to 3/11 : the number of dates in feb and no of dates in mar
2016/3/25  0     0    7     21    //date from 3/25 to 4/21 : the number of dates in mar and no of dates in apr
</code>```

get 30 days after the df["date"]

df["date"] + timedelta(month=1)

count the frequency of months which belong to the specific 30 days

Is there any method to do this quickly?

Thanks.

答:
Just go step by step.  First you offset your original date by + pd.to_timedelta('30d').  Then create a column indicating the month only by df.date.dt.month.  Then create a column with the end-of-month date for each date - some ideas for that are here: Want the last day of each month for a data frame in pandas.  Finally, fill in a matrix where the columns are the 12 months, setting the values in the columns for the month and month+1.

By enriching your DataFrame one column at a time, you can easily move from your input to your desired output.  There is not likely to be a magic method that does everything in a single call.

Read all about date/time functions in Pandas here: https://pandas.pydata.org/pandas-docs/stable/timeseries.html - there are a lot!

ContentLicense: CC BY-SA 3.0

Body:
I have a dataframe containing date, and I would like to process the data as follow for feature engineering

df

date
2016/1/1
2015/2/10
2016/4/5

after process I would like to make the df looks like

date      Jan    Feb   Mar   Apr
2016/1/1  30     0    0      0    //date from 1/1 to 1/30 : the number of dates in jan
2015/2/10  0     19   11     0    //date from 2/10 to 3/11 : the number of dates in feb and no of dates in mar
2016/3/25  0     0    7     21    //date from 3/25 to 4/21 : the number of dates in mar and no of dates in apr

get 30 days after the df["date"]

df["date"] + timedelta(month=1)

count the frequency of months which belong to the specific 30 days

Is there any method to do this quickly?

Thanks.


问:
C++ container for heterogeneous POD types
Is there a form of heterogeneous container, that is able to to store for example different primitive types (such as int, float, double)?

Ultimately I'd like to be able to use the elements in calculations without referring to the type explicitly, for example auto res = a + b, where the operands a and b are elements pulled out of the container and could be of same or different types.

答:
With C++17 you can use std::any with any container. With older C++ versions you can use boost::any.</p>

```<code>#include <iostream>
#include <vector>
#include <any>

struct A
{
    int a;
    explicit operator int() const { return a; }
};

struct B
{
    double b;
    explicit operator double() const { return b; }
};

int main()
{
    A a{ 5 };
    B b{ 6.};

    std::vector<std::any> v;
    v.push_back(3 );
    v.push_back(4.);
    v.push_back(a );
    v.push_back(b );

    for (auto const e : v)
    {
        if (e.type() == typeid(double))
            std::cout << std::any_cast<double>(e) << std::endl;

        if (e.type() == typeid(B))
            std::cout << (double)std::any_cast<B>(e) << std::endl;
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
With C++17 you can use std::any with any container. With older C++ versions you can use boost::any.

#include <iostream>
#include <vector>
#include <any>

struct A
{
    int a;
    explicit operator int() const { return a; }
};

struct B
{
    double b;
    explicit operator double() const { return b; }
};

int main()
{
    A a{ 5 };
    B b{ 6.};

    std::vector<std::any> v;
    v.push_back(3 );
    v.push_back(4.);
    v.push_back(a );
    v.push_back(b );

    for (auto const e : v)
    {
        if (e.type() == typeid(double))
            std::cout << std::any_cast<double>(e) << std::endl;

        if (e.type() == typeid(B))
            std::cout << (double)std::any_cast<B>(e) << std::endl;
    }
}


问:
Generic List AddRange() type safety
Ironically, while converting a bunch of old Arraylists to use generic List(Of foo) collections, to improve type safety, I encountered an unexpected behaviour in the List.AddRange() method.

Given the following code, I would have expected a compiler error, but I don't get one, and the project runs until the AddRange call, where an 'Unable to cast List(Of bar) to List(Of foo)' exception is thrown.

```<code>Dim barList As List(Of bar) = BarFunctionsLib.GetBarList()

Dim fooList As New List(Of foo)
fooList.AddRange(barList)
</code>```

Shouldn't my attempt to pass a List(Of bar) into an AddRange method on a List(Of foo) be picked up by the compiler? I've not been through my compiler settings in VS2015, perhaps they've been fiddled with in the past and now let this through?

Any ideas would be appreciated, as the whole justification of putting work into converting Arraylists to generic Lists was to prevent errors like this.

答:
You need to turn on Option Strict to get a compiler error about this - the simplest way is to put

```<code>Option Strict On
</code>```

at the top of your source file.

A more robust solution for existing projects is to go to your project properties, and in the Compile section set it globally for your project.

As Tim mentioned in a comment however, the very best solution is to change your settings to default it on for all new VB projects:

Title: Generic List AddRange() type safety

Body:
Ironically, while converting a bunch of old Arraylists to use generic List(Of foo) collections, to improve type safety, I encountered an unexpected behaviour in the List.AddRange() method.

Given the following code, I would have expected a compiler error, but I don't get one, and the project runs until the AddRange call, where an 'Unable to cast List(Of bar) to List(Of foo)' exception is thrown.

Dim barList As List(Of bar) = BarFunctionsLib.GetBarList()

Dim fooList As New List(Of foo)
fooList.AddRange(barList)

Shouldn't my attempt to pass a List(Of bar) into an AddRange method on a List(Of foo) be picked up by the compiler? I've not been through my compiler settings in VS2015, perhaps they've been fiddled with in the past and now let this through?

Any ideas would be appreciated, as the whole justification of putting work into converting Arraylists to generic Lists was to prevent errors like this.

Body:
You need to turn on Option Strict to get a compiler error about this - the simplest way is to put

Option Strict On

at the top of your source file.

A more robust solution for existing projects is to go to your project properties, and in the Compile section set it globally for your project.

As Tim mentioned in a comment however, the very best solution is to change your settings to default it on for all new VB projects:


问:
Error compiling Octave in Centos 7
Here is a list of the steps that I did in order to attempt to install Octave 4.2.1 in Centos 7 (repo version is 3.8.2 which is really old now)

```<code>1)   yum update
2)   yum-builddep -y octave
3)   yum -y install qt-devel mercurial gcc-c++ lapack-devel libtool
4)   yum -y install epstool transfig pstoedit qscintilla-devel

(NOTE: First problem was right here as there is NO pstoedit in Centos 7, as far as I know)

5) sudo yum install bzip2-devel atlas-devel libsndfile-devel portaudio-devel GraphicsMagick-c++-devel
6)  ln -s /usr/lib64/atlas/libtatlas.so /usr/lib64/libatlas.so (One of the tutorials recommended doing this to fix a place where a library was being searched for or something like that. It seemed harmless enough)
7) wget ftp://ftp.gnu.org/gnu/octave/octave-4.2.1.tar.gz
8) tar-xvf octave-4.2.1.tar.lz
9) cd octave-4.2.1
10) export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk
11) ./configure --prefix=/usr/local/octave/versions/4.2.1
12)  make -j4
</code>```

It failed with this error:

```<code>In file included from libgui/src/settings-dialog.cc:31:0:
libgui/src/ui-settings-dialog.h:13:29: fatal error: QtWidgets/QAction: No such file or directory
 #include <QtWidgets/QAction>
</code>```

Has anyone come up with this problem and has some workaround or solution? Thanks

答: QtWidgets/QAction is specific to Qt5, and it seems that when you executed yum-builddep -y octave it got dependencies for Qt4. Configure octave with the option --with-qt=4. Another option is to install qt5 libraries and its devel files, configure --with-qt=5, and make.

Title: Error compiling Octave in Centos 7

Body:
Here is a list of the steps that I did in order to attempt to install Octave 4.2.1 in Centos 7 (repo version is 3.8.2 which is really old now)

1)   yum update
2)   yum-builddep -y octave
3)   yum -y install qt-devel mercurial gcc-c++ lapack-devel libtool
4)   yum -y install epstool transfig pstoedit qscintilla-devel

(NOTE: First problem was right here as there is NO pstoedit in Centos 7, as far as I know)

5) sudo yum install bzip2-devel atlas-devel libsndfile-devel portaudio-devel GraphicsMagick-c++-devel
6)  ln -s /usr/lib64/atlas/libtatlas.so /usr/lib64/libatlas.so (One of the tutorials recommended doing this to fix a place where a library was being searched for or something like that. It seemed harmless enough)
7) wget ftp://ftp.gnu.org/gnu/octave/octave-4.2.1.tar.gz
8) tar-xvf octave-4.2.1.tar.lz
9) cd octave-4.2.1
10) export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk
11) ./configure --prefix=/usr/local/octave/versions/4.2.1
12)  make -j4

It failed with this error:

In file included from libgui/src/settings-dialog.cc:31:0:
libgui/src/ui-settings-dialog.h:13:29: fatal error: QtWidgets/QAction: No such file or directory
 #include <QtWidgets/QAction>

Has anyone come up with this problem and has some workaround or solution? Thanks


问:
Espresso checking if toasts are displayed (one on top of another)
I have an problem with checking if toast is displayed using espresso. I'm using class:

```<code>       import android.os.IBinder;
    import android.support.test.espresso.Root;
    import android.view.WindowManager;
    import org.hamcrest.Description;
    import org.hamcrest.TypeSafeMatcher;

    public class ToastMatcher extends TypeSafeMatcher<Root> {

    @Override
    public void describeTo(Description description) {
        description.appendText("is toast");
    }

    @Override
    public boolean matchesSafely(Root root) {
        int type = root.getWindowLayoutParams().get().type;
        if ((type == WindowManager.LayoutParams.TYPE_TOAST)) {
            IBinder windowToken = root.getDecorView().getWindowToken();
            IBinder appToken = root.getDecorView().getApplicationWindowToken();
            if (windowToken == appToken) {
                // windowToken == appToken means this window isn't contained by any other windows.
                // if it was a window for an activity, it would have TYPE_BASE_APPLICATION.
                return true;
            }
        }
        return false;
    }

}
</code>```

and checking Toast by:

```<code>onView(withText(R.string.unauthorized)).inRoot(new ToastMatcher())
            .check(matches(isDisplayed()));
</code>```

Everything works fine until I try to check another toast in the same class for example:

```<code>@Test
public void messageOnBack() throws Exception{
pressBack();
onView(withText(R.string.exit_on_back)).inRoot(new ToastMatcher())
            .check(matches(isDisplayed()));
</code>```

Then first one is passed but second one puts error:

```<code>    android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with string from resource id: <2131165323>[unauthorized] value: Wrong login or password.

View Hierarchy:
+>LinearLayout{id=-1, visibility=VISIBLE, width=660, height=116, has-focus=false, has-focusable=false, has-window-focus=false, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}
|
+->AppCompatTextView{id=16908299, res-name=message, visibility=VISIBLE, width=528, height=58, has-focus=false, has-focusable=false, has-window-focus=false, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=66.0, y=29.0, text=Please click BACK again to exit., input-type=0, ime-target=false, has-links=false}
|
at dalvik.system.VMStack.getThreadStackTrace(Native Method)
</code>```

What is weird, when I comment out one of the tests second one works just fine without any changes. Espresso seems to get stupid when one toast is displayed on top of another. Any ideas how to solve this?

答:
The problem is that the previously shown toast is showing while you are testing for the second one. You can solve this by making a mToast member variable visible for testing, and use that to cancel any active toast in @After, like this:

When showing toast (the production code for the Activity under test):

```<code>@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
Toast mToast;

private void showToast(final String text) {
    mToast = Toast.makeText(this, text, Toast.LENGTH_LONG);
    mToast.show();
}
</code>```

The test code (in the same package as the code under test):

```<code>    @After
    public void tearDown() {
        // Remove any toast message that is still shown:
        Toast toast = mActivityRule.getActivity().mToast;
        if (toast != null) {
            toast.cancel();
        }
    }
</code>```

This will require you to change the production code a tiny bit, but using @VisibleForTesting in the latest version of Android Studio will give error if you use the member variable elsewhere.

Body:
I have an problem with checking if toast is displayed using espresso. I'm using class:

       import android.os.IBinder;
    import android.support.test.espresso.Root;
    import android.view.WindowManager;
    import org.hamcrest.Description;
    import org.hamcrest.TypeSafeMatcher;

    public class ToastMatcher extends TypeSafeMatcher<Root> {

    @Override
    public void describeTo(Description description) {
        description.appendText("is toast");
    }

    @Override
    public boolean matchesSafely(Root root) {
        int type = root.getWindowLayoutParams().get().type;
        if ((type == WindowManager.LayoutParams.TYPE_TOAST)) {
            IBinder windowToken = root.getDecorView().getWindowToken();
            IBinder appToken = root.getDecorView().getApplicationWindowToken();
            if (windowToken == appToken) {
                // windowToken == appToken means this window isn't contained by any other windows.
                // if it was a window for an activity, it would have TYPE_BASE_APPLICATION.
                return true;
            }
        }
        return false;
    }

}

and checking Toast by:

onView(withText(R.string.unauthorized)).inRoot(new ToastMatcher())
            .check(matches(isDisplayed()));

Everything works fine until I try to check another toast in the same class for example:

@Test
public void messageOnBack() throws Exception{
pressBack();
onView(withText(R.string.exit_on_back)).inRoot(new ToastMatcher())
            .check(matches(isDisplayed()));

Then first one is passed but second one puts error:

    android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with string from resource id: <2131165323>[unauthorized] value: Wrong login or password.

View Hierarchy:
+>LinearLayout{id=-1, visibility=VISIBLE, width=660, height=116, has-focus=false, has-focusable=false, has-window-focus=false, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}
|
+->AppCompatTextView{id=16908299, res-name=message, visibility=VISIBLE, width=528, height=58, has-focus=false, has-focusable=false, has-window-focus=false, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=66.0, y=29.0, text=Please click BACK again to exit., input-type=0, ime-target=false, has-links=false}
|
at dalvik.system.VMStack.getThreadStackTrace(Native Method)

What is weird, when I comment out one of the tests second one works just fine without any changes. Espresso seems to get stupid when one toast is displayed on top of another. Any ideas how to solve this?

Body:
The problem is that the previously shown toast is showing while you are testing for the second one. You can solve this by making a mToast member variable visible for testing, and use that to cancel any active toast in @After, like this:

When showing toast (the production code for the Activity under test):

@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
Toast mToast;

private void showToast(final String text) {
    mToast = Toast.makeText(this, text, Toast.LENGTH_LONG);
    mToast.show();
}

The test code (in the same package as the code under test):

    @After
    public void tearDown() {
        // Remove any toast message that is still shown:
        Toast toast = mActivityRule.getActivity().mToast;
        if (toast != null) {
            toast.cancel();
        }
    }

This will require you to change the production code a tiny bit, but using @VisibleForTesting in the latest version of Android Studio will give error if you use the member variable elsewhere.


问:
Angular2 Logging
I am looking to introduce logging to an angular2 app and want to check any good libraries or approaches you could recommend on this.

Requirements for logging are:

Will have options configure logging like info, warn, error, debug and verbose.

Will be able to keep logs into local storage and then after a certain interval sync the logs to a server end point

Will be able to support Json format and have control over the log format

Requirement below would be nice to have and any experience on working with web worker that you can share would be appreciated.

Would be nice to have the logging function build as a web-worker so away from browser thread and we could potentially use app cache as temporary storage?

Any advice on this would be much appreciated.

答:
I think JSNLog partly matches your requirements (I am the author of JSNLog).

JSNLog consists of a client side library jsnlog.js and a server side component. The client side library sends log items to the server side component in AJAX requests. Once on the server, the log items are stored in your server side log. The .Net 4.x version uses Common.Logging, to support Log4Net, NLog, Elmah and Serilog logs. The .Net Core version supports the Core logging framework.

Matching JSNLog features with your requirements:

Will have options configure logging like info, warn, error, debug and
  verbose.

JSNLog supports Log4Net severity levels: Trace, Debug, Info, Warn,
   Error, Fatal. Additionally, you can use numeric severity levels,
   giving you as many severity levels as you want.

Will be able to keep logs into local storage and then after a certain
  interval sync the logs to a server end point

JSNLog allows you to batch a configurable number of log items in each message to the server. It also supports setting a maximum time that any message sits in the buffer before being sent.

Additionally, JSNLog lets you store log items of low severity in client side memory, and only send them to the server when a high severity log item is sent. For example, you can log Trace events in case an exception happens, and only send them to the server when an exception does happen and logs a Fatal event.

Will be able to support Json format and have control over the log
  format

JSNLog allows you to log JSON objects. If you use Serilog on the server, you can store these objects as objects rather than strings. Also, you can set an event handler on jsnlog.js that allows you to modify the outgoing log item.

Would be nice to have the logging function build as a web-worker ...

JSNLog isn't a web worker.

Title: Angular2 Logging


问:
syntax to access in a ragged array ?
I saw this post about making a ragged array.

when I try to do that everything work until I want to access this array.

```<code>type :: vector
    integer, dimension(:), allocatable :: elements
end type vector
type :: ragged_array
    type(vector), dimension(:), allocatable :: vectors
end type ragged_array
type(ragged_array) :: ragarr
allocate(ragarr%vectors(1)%elements(3))
allocate(ragarr%vectors(2)%elements(4))
!PROBLEM HERE :
raggar(1,1:3)=0
raggar(2,1:4)=1
</code>```

It give me error :

```<code>The assigment operation or the binary expression operation is invalid for the data type of two operands
</code>```

It's still unclear for me how to manipulate this ragged array, how do I access a specific value... thanks for any help !

答:
Your code contains many errors:

You should allocate raggar%vectors before allocate its components raggar%vectors%elements.

raggar is a scalar which contains allocatable array which contains allocatable array and it is not an array, if you want to access its elements you can only use raggar%vectors(i)%elements(j)

Corrected code:

```<code>type :: vector
    integer, dimension(:), allocatable :: elements
end type vector

type :: ragged_array
    type(vector), dimension(:), allocatable :: vectors
end type ragged_array

type(ragged_array) :: ragarr

allocate( raggar%vectors(2) )
allocate( ragarr%vectors(1)%elements(3) )
allocate( ragarr%vectors(2)%elements(4) )

!PROBLEM HERE :
raggar%vectors(1)%elements=0 !raggar(1,1:3)=0
raggar%vectors(2)%elements=0 !raggar(2,1:4)=1
</code>```

Title: syntax to access in a ragged array ?

Body:
I saw this post about making a ragged array.

when I try to do that everything work until I want to access this array.

type :: vector
    integer, dimension(:), allocatable :: elements
end type vector
type :: ragged_array
    type(vector), dimension(:), allocatable :: vectors
end type ragged_array
type(ragged_array) :: ragarr
allocate(ragarr%vectors(1)%elements(3))
allocate(ragarr%vectors(2)%elements(4))
!PROBLEM HERE :
raggar(1,1:3)=0
raggar(2,1:4)=1

It give me error :

The assigment operation or the binary expression operation is invalid for the data type of two operands

It's still unclear for me how to manipulate this ragged array, how do I access a specific value... thanks for any help !

Body:
Your code contains many errors:

You should allocate raggar%vectors before allocate its components raggar%vectors%elements.

raggar is a scalar which contains allocatable array which contains allocatable array and it is not an array, if you want to access its elements you can only use raggar%vectors(i)%elements(j)

Corrected code:

type :: vector
    integer, dimension(:), allocatable :: elements
end type vector

type :: ragged_array
    type(vector), dimension(:), allocatable :: vectors
end type ragged_array

type(ragged_array) :: ragarr

allocate( raggar%vectors(2) )
allocate( ragarr%vectors(1)%elements(3) )
allocate( ragarr%vectors(2)%elements(4) )

!PROBLEM HERE :
raggar%vectors(1)%elements=0 !raggar(1,1:3)=0
raggar%vectors(2)%elements=0 !raggar(2,1:4)=1


问:
How to navigate to a resource by path from the xml file in IntelliJ Idea?
I have an xml file (src/main/resources/all_suites.xml) with information about test suites for TestNG framework. It looks like this:

```<code><!-- shopping, booking and retrieve-->
<suiteRef path="suite_shopping_create_order_retrieve.xml"/>

<!-- shopping, booking and fulfillment-->
<suiteRef path="suite_shopping_booking_air.xml"/>
</code>```

All these references point to existing files with specific test cases. They are located in the same place (src/main/resources/)

In Eclipse I can hover each path value (e.g. suite_shopping_booking_air.xml), click left mouse button and the corresponding file will be opened in the editor.

https://gyazo.com/d95ef56fc2fd43c9d0cb81fcdf8094e8

How can do the same thing in Idea Community Edition?

P.S. I know about all Idea navigation opportunities (Ctrl+N, Ctrl+Shift+N and etc) but they don't satisfy me.

Thanks in advance.

答:
If you check the TestNG DTD, you will not find suiteRef there.

IntelliJ IDEA supports suite-file and suite-files navigation.

Body:
I have an xml file (src/main/resources/all_suites.xml) with information about test suites for TestNG framework. It looks like this:

<suiteRef path="suite_shopping_create_order_retrieve.xml"/>

<suiteRef path="suite_shopping_booking_air.xml"/>

All these references point to existing files with specific test cases. They are located in the same place (src/main/resources/)

In Eclipse I can hover each path value (e.g. suite_shopping_booking_air.xml), click left mouse button and the corresponding file will be opened in the editor.

https://gyazo.com/d95ef56fc2fd43c9d0cb81fcdf8094e8

How can do the same thing in Idea Community Edition?

P.S. I know about all Idea navigation opportunities (Ctrl+N, Ctrl+Shift+N and etc) but they don't satisfy me.

Thanks in advance.


问:
Java Iterator hasNext strange behavior
I have the following code:

```<code>  Set<OWLNamedIndividual> individuals = reasoner.getInstances( tClass, false ).getFlattened();
  for(OWLNamedIndividual it1 : individuals)
       {
     NodeSet<OWLNamedIndividual> names = reasoner.getObjectPropertyValues( it1, obj1 );
         System.out.println(it1.getIRI().getShortForm() + " has objects:");
     for(Node<OWLNamedIndividual> it2: names)
         {
          Iterator iter=it2.iterator();
          while(iter.hasNext())
           {
            System.out.print("\t");
            System.out.println(iter.next().toString());
               System.out.println(iter.hasNext());
           }
         }
       }
</code>```

that returns the following:

```<code>name has objects:
<http://www.test/#name>
     false
<http://www.test/#name2>
     false
</code>```

The inner hasNext seams not working while the outer do. I need to check for the last iteration. What is the issue here ? Many thanks.

答: There is no problem here. When you call next(), the value of hasNext() can change. The last time through it will print as false. In this case each outer collection appears to have only one element each.

Title: Java Iterator hasNext strange behavior

Body:
I have the following code:

  Set<OWLNamedIndividual> individuals = reasoner.getInstances( tClass, false ).getFlattened();
  for(OWLNamedIndividual it1 : individuals)
       {
     NodeSet<OWLNamedIndividual> names = reasoner.getObjectPropertyValues( it1, obj1 );
         System.out.println(it1.getIRI().getShortForm() + " has objects:");
     for(Node<OWLNamedIndividual> it2: names)
         {
          Iterator iter=it2.iterator();
          while(iter.hasNext())
           {
            System.out.print("\t");
            System.out.println(iter.next().toString());
               System.out.println(iter.hasNext());
           }
         }
       }

that returns the following:

name has objects:
<http://www.test/#name>
     false
<http://www.test/#name2>
     false

The inner hasNext seams not working while the outer do. I need to check for the last iteration. What is the issue here ? Many thanks.


问:
Datatables get value of searchable on a column
I have created a datatable with following code:

userTable = $('#userTable').DataTable({
                serverSide: true,
                processing: true,
                ajax: {
                        url: "{!! route('listOfUsersAjax') !!}",
                        type: "GET",
                        dataSrc: function ( json ) {
                          //console.log(json);;
                            for ( var i=0, ien=json.data.length ; i<ien ; i++ ) {
                                if (json.data[i].is_manager == 1){
                                    json.data[i].is_manager = 'Yes';
                                }
                                else {
                                    json.data[i].is_manager = 'No';
                                }
                            }
                            return json.data;
                        }
                    },
                columns: [
                    {
                        className:      'details-control',
                        orderable:      false,
                        searchable:     false,
                        data:           null,
                        defaultContent: ''
                    },
                    { name: 'id', data: 'id' },
                    { name: 'name', data: 'name' },
                    { name: 'email', data: 'email' },
                    { name: 'is_manager', data: 'is_manager'},
                    { name: 'region', data: 'region' },
                    { name: 'country', data: 'country' },
                    { name: 'domain', data: 'domain' },
                    { name: 'management_code', data: 'management_code' },
                    { name: 'job_role', data: 'job_role' },
                    { name: 'employee_type', data: 'employee_type' },
                    {
                        name: 'actions',
                        data: null,
                        sortable: false,
                        searchable: false,
                        render: function (data) {
                            var actions = '';
                            actions += '
';
                            actions += '<button data-toggle="tooltip" title="view" id="'+data.id+'" class="buttonView btn btn-success"></button>';
                            actions += '<button data-toggle="tooltip" title="edit" id="'+data.id+'" class="buttonUpdate btn btn-primary"></button>';
                            actions += '<button data-toggle="tooltip" title="delete" id="'+data.id+'" class="buttonDelete btn btn-danger"></button>';
                            actions += '
';
                            return actions;
                        }
                    }
                    ],
                columnDefs: [
                    {
                        "targets": [1,3,4], "visible": false, "searchable": false
                    }
                    ],
                order: [[2, 'asc']],
                initComplete: function () {
                    this.api().columns().every(function () {
                        var column = this;
                        //console.log(userTable);
                        // Now we need to skip the first column as it is used for the drawer...
                        if(column[0][0] == '0' || column[0][0] == '11'){return true;};
                        var input = document.createElement("input");
                        $(input).appendTo($(column.footer()).empty())
                        .on('keyup change', function () {
                            column.search($(this).val(), false, false, true).draw();
                        });
                    });
                }
            } );
```

At the end, you can see that I have put a initComplete to have search columns to be at the bottom of each column.

I don't need to have a search when the column is not searchable, for example, first column and last one because it is not searchable. I am using the number of the column and returning true so that it doesn't create it but I would like something more dynamic and have an if column searchable is false then return true that way I don't need to specify the number of the column.

Thanks for your help.

答:
You do have the columns definition available through this.api().init().columns. So all you have to do is to evaluate if a columns searchable explicit is set to false (not defining searchable or not defining the column at all means true, since this is the default) :

initComplete: function() {
  var columns = this.api().init().columns;
  this.api().columns().every(function(index) {
    if (!columns[index] || columns[index].searchable) {
       // column is searchable
     } else {
       // column is not searchable
     }
   })
 }
```

Body:
I have created a datatable with following code:

userTable = $('#userTable').DataTable({
                serverSide: true,
                processing: true,
                ajax: {
                        url: "{!! route('listOfUsersAjax') !!}",
                        type: "GET",
                        dataSrc: function ( json ) {
                          //console.log(json);;
                            for ( var i=0, ien=json.data.length ; i<ien ; i++ ) {
                                if (json.data[i].is_manager == 1){
                                    json.data[i].is_manager = 'Yes';
                                }
                                else {
                                    json.data[i].is_manager = 'No';
                                }
                            }
                            return json.data;
                        }
                    },
                columns: [
                    {
                        className:      'details-control',
                        orderable:      false,
                        searchable:     false,
                        data:           null,
                        defaultContent: ''
                    },
                    { name: 'id', data: 'id' },
                    { name: 'name', data: 'name' },
                    { name: 'email', data: 'email' },
                    { name: 'is_manager', data: 'is_manager'},
                    { name: 'region', data: 'region' },
                    { name: 'country', data: 'country' },
                    { name: 'domain', data: 'domain' },
                    { name: 'management_code', data: 'management_code' },
                    { name: 'job_role', data: 'job_role' },
                    { name: 'employee_type', data: 'employee_type' },
                    {
                        name: 'actions',
                        data: null,
                        sortable: false,
                        searchable: false,
                        render: function (data) {
                            var actions = '';
                            actions += '
';
                            actions += '<button data-toggle="tooltip" title="view" id="'+data.id+'" class="buttonView btn btn-success"></button>';
                            actions += '<button data-toggle="tooltip" title="edit" id="'+data.id+'" class="buttonUpdate btn btn-primary"></button>';
                            actions += '<button data-toggle="tooltip" title="delete" id="'+data.id+'" class="buttonDelete btn btn-danger"></button>';
                            actions += '
';
                            return actions;
                        }
                    }
                    ],
                columnDefs: [
                    {
                        "targets": [1,3,4], "visible": false, "searchable": false
                    }
                    ],
                order: [[2, 'asc']],
                initComplete: function () {
                    this.api().columns().every(function () {
                        var column = this;
                        //console.log(userTable);
                        // Now we need to skip the first column as it is used for the drawer...
                        if(column[0][0] == '0' || column[0][0] == '11'){return true;};
                        var input = document.createElement("input");
                        $(input).appendTo($(column.footer()).empty())
                        .on('keyup change', function () {
                            column.search($(this).val(), false, false, true).draw();
                        });
                    });
                }
            } );

At the end, you can see that I have put a initComplete to have search columns to be at the bottom of each column.

I don't need to have a search when the column is not searchable, for example, first column and last one because it is not searchable. I am using the number of the column and returning true so that it doesn't create it but I would like something more dynamic and have an if column searchable is false then return true that way I don't need to specify the number of the column.

Thanks for your help.


问:
How get the sequences properly indented with ruamel.yaml?
With the following data

```<code>from ruamel import yaml
data = {1: {1:[{1:1,2:2},{1:1,2:2}], 2:2}, 2: 42}
</code>```

I get an incorrect indentation for the sequence

```<code>>>> print yaml.round_trip_dump(data)
1:
  1:
  - 1: 1
    2: 2
  - 1: 1
    2: 2
  2: 2
2: 42
</code>```

Which cannot be folded on Notepad++. However with the proper indent it works:

Bad:

Good:

I have tried to use block_seq_indent=2:

```<code>>>> print yaml.round_trip_dump(data, block_seq_indent=2)
1:
  1:
    - 1: 1
    2: 2
    - 1: 1
    2: 2
  2: 2
2: 42
</code>```

How can I solve this issue?

答:
The ruamel.yaml documentation, although generally lacking, says the following about offset of the dash within the indent:

If the offset equals sequence, there is not enough room for the dash and the space that has to follow it. In that case the element itself would normally be pushed to the next line (and older versions of ruamel.yaml did so). But this is prevented from happening. However the indent level is what is used for calculating the cumulative indent for deeper levels and specifying sequence=3 resp. offset=2, might give correct, but counter intuitive results.

It is best to always have sequence >= offset + 2 but this is not enforced. Depending on your structure, not following this advice might lead to invalid output.

By default indent (both for mappings and for sequences) equals 2, if you do:

```<code>import sys
from ruamel import yaml

data = {1: {1:[{1:1,2:2},{1:1,2:2}], 2:2}, 2: 42}

yml = yaml.YAML()
yml.indent(mapping=2, sequence=4, offset=2)
yml.dump(data, sys.stdout)
</code>```

you get:

```<code>1:
  1:
    - 1: 1
      2: 2
    - 1: 1
      2: 2
  2: 2
2: 42
</code>```

With the old API, that you use in your question, you cannot do the different indent for mappings and sequences in a trivial way (you need to subclass the Emitter, and on post __init__ of the base class, set the values). And with older versions of ruamel.yaml this was not possible at all.

This only works with the default (round-trip, i.e. typ='rt') dumper, but does work with both the normal Python dict resp. list (e.g. from YAML(typ='safe').load(....)) and the
more convulated subclasses thereof used when doing YAML().load(....)

(the above requires ruamel.yaml>=0.15.30)

Body:
With the following data

from ruamel import yaml
data = {1: {1:[{1:1,2:2},{1:1,2:2}], 2:2}, 2: 42}

I get an incorrect indentation for the sequence

>>> print yaml.round_trip_dump(data)
1:
  1:
  - 1: 1
    2: 2
  - 1: 1
    2: 2
  2: 2
2: 42

Which cannot be folded on Notepad++. However with the proper indent it works:

Bad:

Good:

I have tried to use block_seq_indent=2:

>>> print yaml.round_trip_dump(data, block_seq_indent=2)
1:
  1:
    - 1: 1
    2: 2
    - 1: 1
    2: 2
  2: 2
2: 42

How can I solve this issue?

Body:
The ruamel.yaml documentation, although generally lacking, says the following about offset of the dash within the indent:

If the offset equals sequence, there is not enough room for the dash and the space that has to follow it. In that case the element itself would normally be pushed to the next line (and older versions of ruamel.yaml did so). But this is prevented from happening. However the indent level is what is used for calculating the cumulative indent for deeper levels and specifying sequence=3 resp. offset=2, might give correct, but counter intuitive results.

It is best to always have sequence >= offset + 2 but this is not enforced. Depending on your structure, not following this advice might lead to invalid output.

By default indent (both for mappings and for sequences) equals 2, if you do:

import sys
from ruamel import yaml

data = {1: {1:[{1:1,2:2},{1:1,2:2}], 2:2}, 2: 42}

yml = yaml.YAML()
yml.indent(mapping=2, sequence=4, offset=2)
yml.dump(data, sys.stdout)

you get:

1:
  1:
    - 1: 1
      2: 2
    - 1: 1
      2: 2
  2: 2
2: 42

With the old API, that you use in your question, you cannot do the different indent for mappings and sequences in a trivial way (you need to subclass the Emitter, and on post __init__ of the base class, set the values). And with older versions of ruamel.yaml this was not possible at all.

This only works with the default (round-trip, i.e. typ='rt') dumper, but does work with both the normal Python dict resp. list (e.g. from YAML(typ='safe').load(....)) and the
more convulated subclasses thereof used when doing YAML().load(....)

(the above requires ruamel.yaml>=0.15.30)


问:
Magento - Fetch current domain and not base domain
We are running one Magento install over multiple domains and are using a script to fetch information from the database to help users filter the products.

In our coding we have the $_SERVER function calling the store which seems to be store 1 (which is on domain 1), I was wondering what I would need to change to fetch the information from store 2 (which is on domain 2).

答:
If you have multiple domains then presumably you have multiple stores. Rather than reading the domain to determine which store you can just read the store directly:

```<code>$store = Mage::app()->getStore()
</code>```

$store then has all the information you need. For example, to retrieve the 'store code' that you set in the admin use,

```<code>$store->getCode()
</code>```

As well as being object-orientated and hence easier to write, you benefit from the domains being completely configurable from admin, there will be no need to rewrite your code every time there is a change.

Body:
If you have multiple domains then presumably you have multiple stores. Rather than reading the domain to determine which store you can just read the store directly:

$store = Mage::app()->getStore()

$store then has all the information you need. For example, to retrieve the 'store code' that you set in the admin use,

$store->getCode()

As well as being object-orientated and hence easier to write, you benefit from the domains being completely configurable from admin, there will be no need to rewrite your code every time there is a change.

ContentLicense: CC BY-SA 2.5


问:
Download and install apk (without publishing in playstore) from the Instant App
I have uploaded .apk file to the dropbox. I want to download and launch app when user clicks an install button in the Instant App. But the following exception occurs after call to startActivity():

Caused by: java.lang.SecurityException: Permission Denial: opening provider android.support.v4.content.FileProvider from ProcessRecord{8593d11 2399:com.google.android.packageinstaller/u0a26} (pid=2399, uid=10026) that is not exported from uid 10298

```<code>Intent intent = new Intent(Intent.ACTION_VIEW);
if (intent.resolveActivity(getPackageManager()) == null) {
    Log.e("No Packate Manager", intent.getPackage() + "");
    return;
}

Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {  //BuildConfig.APPLICATION_ID
    // File file = new File(File folder, "app-debug.apk");
    //uri = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".fileprovider", file);
    uri = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".fileprovider", new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "app-debug.apk"));
    List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resInfoList) {
        String packageName = resolveInfo.activityInfo.packageName;
        grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }
} else {
    // uri = Uri.fromFile(new File("/mnt/sdcard/Download/app-debug.apk"));
    File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    File outputFile = new File(folder, "app-debug.apk");
    uri = Uri.fromFile(outputFile);
}

intent.setDataAndType(uri, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// install.setDataAndType(myuri, manager.getMimeTypeForDownloadedFile(downloadId));

startActivity(intent);
</code>```

答:
If you are building an .apk from instant run, it won't run on any other device as it has a feature of hot swapping the changes.

Go to Preferences in Android Studio > Build, Execution, Deployment > Instant Run.

Then you should disable it and then make a build by running.
That .apk will run fine on any device.

Hope that helps.

Body:
I have uploaded .apk file to the dropbox. I want to download and launch app when user clicks an install button in the Instant App. But the following exception occurs after call to startActivity():

Caused by: java.lang.SecurityException: Permission Denial: opening provider android.support.v4.content.FileProvider from ProcessRecord{8593d11 2399:com.google.android.packageinstaller/u0a26} (pid=2399, uid=10026) that is not exported from uid 10298

Intent intent = new Intent(Intent.ACTION_VIEW);
if (intent.resolveActivity(getPackageManager()) == null) {
    Log.e("No Packate Manager", intent.getPackage() + "");
    return;
}

Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {  //BuildConfig.APPLICATION_ID
    // File file = new File(File folder, "app-debug.apk");
    //uri = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".fileprovider", file);
    uri = FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".fileprovider", new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "app-debug.apk"));
    List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resInfoList) {
        String packageName = resolveInfo.activityInfo.packageName;
        grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }
} else {
    // uri = Uri.fromFile(new File("/mnt/sdcard/Download/app-debug.apk"));
    File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    File outputFile = new File(folder, "app-debug.apk");
    uri = Uri.fromFile(outputFile);
}

intent.setDataAndType(uri, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// install.setDataAndType(myuri, manager.getMimeTypeForDownloadedFile(downloadId));

startActivity(intent);


问:
Include Google Font in Rails App
Anyone know how I can include a google fonts style sheet in my rails app? I have tried adding

```<code><link href='https://fonts.googleapis.com/css?family=Raleway:500,900,200'
rel='stylesheet' type='text/css'>
</code>```

Into my application.html.erb but that doesn't do anything

答:
Simply add the code provided by google to the top of your application.scss file.

@import url('https://fonts.googleapis.com/css?family=Quicksand|Rubik');

please note rails will provide you with application.css file out of the box with require statements. remove these and rename application.scss

remember to add @import filename; for any other custome scssfiles in the folder

Title: Include Google Font in Rails App

Body:
Anyone know how I can include a google fonts style sheet in my rails app? I have tried adding

<link href='https://fonts.googleapis.com/css?family=Raleway:500,900,200'
rel='stylesheet' type='text/css'>

Into my application.html.erb but that doesn't do anything


问:
Unable to build adapters using profiles and properties in Maven
I have created an http adapter using mfpdev adapter create
but I found out the adatper.xml configuration file contains server connection configuration which I would like to change accordingly to dev,test,produciton
environment.

So I tried to use maven resource filter by changing the pom.xml as following

pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
<groupId>com.my.adapter</groupId>
<artifactId>MYAPIAdapter</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>adapter</packaging>
<name>MYAPIAdapter</name>

<properties>
    <!-- Use UTF-8 as the encoding of the adapter -->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <!-- MobileFirst adapter deployment properties -->
    <mfpfUrl>http://localhost:9080/mfpadmin</mfpfUrl>
    <mfpfUser>admin</mfpfUser>
    <mfpfPassword>admin</mfpfPassword>
    <mfpfRuntime>mfp</mfpfRuntime>
</properties>

<dependencies>
    <dependency>
        <groupId>com.ibm.mfp</groupId>
        <artifactId>adapter-maven-api</artifactId>
        <scope>provided</scope>
        <version>[8.0.0,9.0.0)</version>
    </dependency>
    <dependency>
        <groupId>com.ibm.mfp</groupId>
        <artifactId>mfp-security-checks-base</artifactId>
        <version>[8.0.0,9.0.0)</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>com.ibm.mfp</groupId>
            <artifactId>adapter-maven-plugin</artifactId>
            <extensions>true</extensions>
        </plugin>
    </plugins>
    <filters>
        <filter>profiles/${build.profile.id}/config.properties</filter>
    </filters>
    <resources>
        <resource>
            <directory>src/main/adapter-resources</directory>
            <filtering>true</filtering>
        </resource>
</resources>
</build>

<profiles>
    <profile>
        <id>pc</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <build.profile.id>pc</build.profile.id>
        </properties>
    </profile>
    <profile>
        <id>sit</id>
        <properties>
            <build.profile.id>sit</build.profile.id>
        </properties>
    </profile>
    <profile>
        <id>uat</id>
        <properties>
            <build.profile.id>uat</build.profile.id>
        </properties>
    </profile>
    <profile>
        <id>prod</id>
        <properties>
            <build.profile.id>prod</build.profile.id>
        </properties>
    </profile>
</profiles>
</code>```

adapter.xml

```<code><mfp:adapter name="MYAPIAdapter"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:mfp="http://www.ibm.com/mfp/integration"
         xmlns:http="http://www.ibm.com/mfp/integration/http">

<displayName>MYAPIAdapter</displayName>
<description>MYAPIAdapter</description>
<connectivity>
    <connectionPolicy xsi:type="http:HTTPConnectionPolicyType">
        <protocol> ${connect.protocol}</protocol>
        <domain> ${connect.domain}</domain>
        <port> ${connect.port}</port>
        <connectionTimeoutInMilliseconds> ${connect.timeout.ms}</connectionTimeoutInMilliseconds>
        <socketTimeoutInMilliseconds> ${connect.sockettimeout.ms}</socketTimeoutInMilliseconds>
        <maxConcurrentConnectionsPerNode> ${max.concurrentconnections}</maxConcurrentConnectionsPerNode>
    </connectionPolicy>
</connectivity>

<procedure name="getFeed"/>
<procedure name="unprotected" secured="false"/>
</code>```

When I run mvn install , I hit following error , seem like mfp maven plugin validate the adapter xml file. I have no problem running with mvn compile and the adapter xml values is succesfully replaced with the values in properties file. Is there anyway to specify the configuration from properties file when building the mfp adapter?

```<code>ERROR] Failed to execute goal com.ibm.mfp:adapter-maven-plugin:8.0.2016082422:build (default-build) on project MYAPIAdapter: Adapter xml file schema validation encountered errors: [cvc-datatype-valid.1.2.1: '${connect.port}' is not a valid value for 'integer'., cvc-type.3.1.3: The value '${connect.port}' of element 'port' is not valid., cvc-datatype-valid.1.2.1: '${connect.timeout.ms}' is not a valid value for 'integer'., cvc-type.3.1.3: The value '${connect.timeout.ms}' of element 'connectionTimeoutInMilliseconds' is not valid., cvc-datatype-valid.1.2.1: '${connect.sockettimeout.ms}' is not a valid value for 'integer'., cvc-type.3.1.3: The value '${connect.sockettimeout.ms}' of element 'socketTimeoutInMilliseconds' is not valid., cvc-datatype-valid.1.2.1: '${max.concurrentconnections}' is not a valid value for 'integer'., cvc-type.3.1.3: The value '${max.concurrentconnections}' of element 'maxConcurrentConnectionsPerNode' is not valid.] -> [Help 1] [ERROR]
</code>```

答:
As a workaround you can set the path to your generated adapter.xml in pom.xml.</p>

```<code>```
<build>
<resources>
  <resource>
    <directory>src/main/adapter-resources</directory>
    <filtering>true</filtering>
    <targetPath>${adapterResourcePath}</targetPath>
  </resource>
  <resource>
    <directory>src/main/resources</directory>
    <filtering>true</filtering>
  </resource>
</resources>
<plugins>
  <plugin>
    <groupId>com.ibm.mfp</groupId>
    <artifactId>adapter-maven-plugin</artifactId>
    <version>${version.mffadapter.plugin}</version>
    <extensions>true</extensions>
    <executions>
      <execution>
        <goals>
          <goal>build</goal>
        </goals>
        <configuration combine.self="override">
          <adapterResourcesDir implementation="java.io.File">${adapterResourcePath}
          </adapterResourcesDir>
        </configuration>
      </execution>
    </executions>
  </plugin>
</code>```

Body:
I have created an http adapter using mfpdev adapter create
but I found out the adatper.xml configuration file contains server connection configuration which I would like to change accordingly to dev,test,produciton
environment.

So I tried to use maven resource filter by changing the pom.xml as following

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
<groupId>com.my.adapter</groupId>
<artifactId>MYAPIAdapter</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>adapter</packaging>
<name>MYAPIAdapter</name>

<properties>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <mfpfUrl>http://localhost:9080/mfpadmin</mfpfUrl>
    <mfpfUser>admin</mfpfUser>
    <mfpfPassword>admin</mfpfPassword>
    <mfpfRuntime>mfp</mfpfRuntime>
</properties>

<dependencies>
    <dependency>
        <groupId>com.ibm.mfp</groupId>
        <artifactId>adapter-maven-api</artifactId>
        <scope>provided</scope>
        <version>[8.0.0,9.0.0)</version>
    </dependency>
    <dependency>
        <groupId>com.ibm.mfp</groupId>
        <artifactId>mfp-security-checks-base</artifactId>
        <version>[8.0.0,9.0.0)</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>com.ibm.mfp</groupId>
            <artifactId>adapter-maven-plugin</artifactId>
            <extensions>true</extensions>
        </plugin>
    </plugins>
    <filters>
        <filter>profiles/${build.profile.id}/config.properties</filter>
    </filters>
    <resources>
        <resource>
            <directory>src/main/adapter-resources</directory>
            <filtering>true</filtering>
        </resource>
</resources>
</build>

<profiles>
    <profile>
        <id>pc</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <build.profile.id>pc</build.profile.id>
        </properties>
    </profile>
    <profile>
        <id>sit</id>
        <properties>
            <build.profile.id>sit</build.profile.id>
        </properties>
    </profile>
    <profile>
        <id>uat</id>
        <properties>
            <build.profile.id>uat</build.profile.id>
        </properties>
    </profile>
    <profile>
        <id>prod</id>
        <properties>
            <build.profile.id>prod</build.profile.id>
        </properties>
    </profile>
</profiles>

adapter.xml

<mfp:adapter name="MYAPIAdapter"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:mfp="http://www.ibm.com/mfp/integration"
         xmlns:http="http://www.ibm.com/mfp/integration/http">

<displayName>MYAPIAdapter</displayName>
<description>MYAPIAdapter</description>
<connectivity>
    <connectionPolicy xsi:type="http:HTTPConnectionPolicyType">
        <protocol> ${connect.protocol}</protocol>
        <domain> ${connect.domain}</domain>
        <port> ${connect.port}</port>
        <connectionTimeoutInMilliseconds> ${connect.timeout.ms}</connectionTimeoutInMilliseconds>
        <socketTimeoutInMilliseconds> ${connect.sockettimeout.ms}</socketTimeoutInMilliseconds>
        <maxConcurrentConnectionsPerNode> ${max.concurrentconnections}</maxConcurrentConnectionsPerNode>
    </connectionPolicy>
</connectivity>

<procedure name="getFeed"/>
<procedure name="unprotected" secured="false"/>

When I run mvn install , I hit following error , seem like mfp maven plugin validate the adapter xml file. I have no problem running with mvn compile and the adapter xml values is succesfully replaced with the values in properties file. Is there anyway to specify the configuration from properties file when building the mfp adapter?

ERROR] Failed to execute goal com.ibm.mfp:adapter-maven-plugin:8.0.2016082422:build (default-build) on project MYAPIAdapter: Adapter xml file schema validation encountered errors: [cvc-datatype-valid.1.2.1: '${connect.port}' is not a valid value for 'integer'., cvc-type.3.1.3: The value '${connect.port}' of element 'port' is not valid., cvc-datatype-valid.1.2.1: '${connect.timeout.ms}' is not a valid value for 'integer'., cvc-type.3.1.3: The value '${connect.timeout.ms}' of element 'connectionTimeoutInMilliseconds' is not valid., cvc-datatype-valid.1.2.1: '${connect.sockettimeout.ms}' is not a valid value for 'integer'., cvc-type.3.1.3: The value '${connect.sockettimeout.ms}' of element 'socketTimeoutInMilliseconds' is not valid., cvc-datatype-valid.1.2.1: '${max.concurrentconnections}' is not a valid value for 'integer'., cvc-type.3.1.3: The value '${max.concurrentconnections}' of element 'maxConcurrentConnectionsPerNode' is not valid.] -> [Help 1] [ERROR]

Body:
As a workaround you can set the path to your generated adapter.xml in pom.xml.

```
<build>
<resources>
  <resource>
    <directory>src/main/adapter-resources</directory>
    <filtering>true</filtering>
    <targetPath>${adapterResourcePath}</targetPath>
  </resource>
  <resource>
    <directory>src/main/resources</directory>
    <filtering>true</filtering>
  </resource>
</resources>
<plugins>
  <plugin>
    <groupId>com.ibm.mfp</groupId>
    <artifactId>adapter-maven-plugin</artifactId>
    <version>${version.mffadapter.plugin}</version>
    <extensions>true</extensions>
    <executions>
      <execution>
        <goals>
          <goal>build</goal>
        </goals>
        <configuration combine.self="override">
          <adapterResourcesDir implementation="java.io.File">${adapterResourcePath}
          </adapterResourcesDir>
        </configuration>
      </execution>
    </executions>
  </plugin>


问:
Returning two values, Tuple vs 'out' vs 'struct'
Consider a function which returns two values. We can write:

```<code>// Using out:
string MyFunction(string input, out int count)

// Using Tuple class:
Tuple<string, int> MyFunction(string input)

// Using struct:
MyStruct MyFunction(string input)
</code>```

Which one is best practice and why?

答:
Adding to the previous answers, C# 7 brings value type tuples, unlike System.Tuple that is a reference type and also offer improved semantics.

You can still leave them unnamed and use the .Item* syntax:

```<code>(string, string, int) getPerson()
{
    return ("John", "Doe", 42);
}

var person = getPerson();
person.Item1; //John
person.Item2; //Doe
person.Item3;   //42
</code>```

But what is really powerful about this new feature is the ability to have named tuples. So we could rewrite the above like this:

```<code>(string FirstName, string LastName, int Age) getPerson()
{
    return ("John", "Doe", 42);
}

var person = getPerson();
person.FirstName; //John
person.LastName; //Doe
person.Age;   //42
</code>```

Destructuring is also supported:

(string firstName, string lastName, int age) = getPerson()

Body:
Consider a function which returns two values. We can write:

// Using out:
string MyFunction(string input, out int count)

// Using Tuple class:
Tuple<string, int> MyFunction(string input)

// Using struct:
MyStruct MyFunction(string input)

Which one is best practice and why?

Body:
Adding to the previous answers, C# 7 brings value type tuples, unlike System.Tuple that is a reference type and also offer improved semantics.

You can still leave them unnamed and use the .Item* syntax:

(string, string, int) getPerson()
{
    return ("John", "Doe", 42);
}

var person = getPerson();
person.Item1; //John
person.Item2; //Doe
person.Item3;   //42

But what is really powerful about this new feature is the ability to have named tuples. So we could rewrite the above like this:

(string FirstName, string LastName, int Age) getPerson()
{
    return ("John", "Doe", 42);
}

var person = getPerson();
person.FirstName; //John
person.LastName; //Doe
person.Age;   //42

Destructuring is also supported:

(string firstName, string lastName, int age) = getPerson()


问:
Java converting int to hex and back again
I have the following code...

```<code>int Val=-32768;
String Hex=Integer.toHexString(Val);
</code>```

This equates to ffff8000

```<code>int FirstAttempt=Integer.parseInt(Hex,16); // Error "Invalid Int"
int SecondAttempt=Integer.decode("0x"+Hex);  // Error "Invalid Int"
</code>```

So, initially, it converts the value -32768 into a hex string ffff8000, but then it can't convert the hex string back into an Integer.

In .Net it works as I'd expect, and returns -32768.

I know that I could write my own little method to convert this myself, but I'm just wondering if I'm missing something, or if this is genuinely a bug?

答:
As Integer.toHexString(byte/integer) is not working when you are trying to convert signed bytes like UTF-16 decoded characters you have to use:

```<code>Integer.toString(byte/integer, 16);
</code>```

or

```<code>String.format("%02X", byte/integer);
</code>```

reverse you can use

```<code>Integer.parseInt(hexString, 16);
</code>```

Body:
I have the following code...

int Val=-32768;
String Hex=Integer.toHexString(Val);

This equates to ffff8000

int FirstAttempt=Integer.parseInt(Hex,16); // Error "Invalid Int"
int SecondAttempt=Integer.decode("0x"+Hex);  // Error "Invalid Int"

So, initially, it converts the value -32768 into a hex string ffff8000, but then it can't convert the hex string back into an Integer.

In .Net it works as I'd expect, and returns -32768.

I know that I could write my own little method to convert this myself, but I'm just wondering if I'm missing something, or if this is genuinely a bug?

Body:
As Integer.toHexString(byte/integer) is not working when you are trying to convert signed bytes like UTF-16 decoded characters you have to use:

Integer.toString(byte/integer, 16);

or

String.format("%02X", byte/integer);

reverse you can use

Integer.parseInt(hexString, 16);


问:
jQuery - Hide DIV which has a span element with certain text inside
I have several divs with the same class names and varying IDs. The ID is not set for the text I need to target

I need to target the Telephone Call text. If the div contains that text, how do I hide the containing div

```<code><div id="rn_FieldDisplay_155" class="rn_FieldDisplay rn_Output">
   <span class="rn_DataLabel">Telephone Call </span>
   <div class="rn_DataValue">No</div>
</div>
</code>```

I have tried the following to no avail

```<code><script>
$(document).ready(function() {
  $(".rn_FieldDisplay > span:contains('Telephone Call')").hide ();
});
</script>
</code>```

答:
Try selecting it's child instead of the element itself :</p>

```<code>$(document).ready(function() {
    $(".rn_FieldDisplay *:contains('Telephone Call')").hide ();
});
</code>```

Body:
I have several divs with the same class names and varying IDs. The ID is not set for the text I need to target

I need to target the Telephone Call text. If the div contains that text, how do I hide the containing div

   Telephone Call

No

I have tried the following to no avail

Body:
Try selecting it's child instead of the element itself :

$(document).ready(function() {
    $(".rn_FieldDisplay *:contains('Telephone Call')").hide ();
});


问:
How to parallelise code with shared writeable memory
I have a program that is is currently quite slow and CPU heavy, and I'm confused about how to parallelise it.

My Problem:

The algorithm works like this (with random numbers):

```<code>import numpy as np
import scipy.spatial as spatial
from collections import Counter

# Particle dictionary
num_parts = int(1e4)
particles = {'coords': np.random.rand(num_parts, 3),
             'flags': np.random.randint(0, 4, size=num_parts)}

# Object dictionary
num_objects = int(1e3)
objects_dict = {'x': [np.random.rand(1)
                      for i in range(0, num_objects)],
                'y': [np.random.rand(1)
                      for i in range(0, num_objects)],
                'z': [np.random.rand(1)
                      for i in range(0, num_objects)],
                'prop_to_calc': [np.array([])
                                 for i in range(0, num_objects)]}

# Build KDTree for particles
tree = spatial.cKDTree(particles['coords'])

# Loop through objects to calculate 'prop_to_calc' based
# on nearby particles flags within radius, r.
r = 0.1
for i in range(0, num_objects):

    # Find nearby indices of particles.
    indices = tree.query_ball_point([objects_dict['x'][i][0],
                                     objects_dict['y'][i][0],
                                     objects_dict['z'][i][0]],
                                    r)

    # Extract flags of nearby particles.
    flags_array = particles['flags'][indices]

    # Find most common flag and store that in property_to_calculate
    c = Counter(flags_array)
    objects_dict['prop_to_calc'] = np.append(objects_dict['prop_to_calc'],
                                             c.most_common(1)[0][0])
</code>```

There are two data sets particles and objects_dict. I want to calculate objects_dict['prop_to_dict'] by searching nearby particles within radius, r and finding their most common flag. This is done with cKDTree and query_ball_point.

For these numbers the time is:
10 loops, best of 3: 55.8 ms per loop in Ipython 4.2.0

However, I want num_parts=1e6 and num_objects=1e5, which results in some serious slow down.

My question:

As it is CPU heavy, I want to try to parallelise it to get some speed up.

I have looked at both multiprocessing and multi threading. However the docs confuse me quite a lot, and I'm not sure how to apply the examples to this problem.

Specifically, I'm concerned with how I share both dictionarys between processes and write into objects_dict at the end.

Thanks for the help in advance.

答:
Try to split the code and make local lists and dictionaries. Union the dictionaries and lists at the end. Just import threading and make a class CalculationThread with subclass threading.Thread and write the parallel code in the method run of the class and start the thread by thread = CalculationThread() and thread.start()

The final code for this is:

```<code>import threading

class CalculationThread(threading Tread):
    def __init__(self, range):
        self.range = range
        # use this copy instead for the thread
        self.objects_dict = dict(objects_dict)
    def run(self):
        for i in self.range:
            # your code

threads = []
threadCount = 8

lastThreadStart = num_objects
tLen = num_objects // threadCount
for i in reversed(range(threadCount)):
    threadStart = i*tLen
    t = CalculationThread(range(threadStart, lastThreadStart))
    lastThreadStart = threadStart

# wait for all to finish
for t in threads: t.join()

# code to union all objects_dicts comes here
</code>```

Body:
I have a program that is is currently quite slow and CPU heavy, and I'm confused about how to parallelise it.

My Problem:

The algorithm works like this (with random numbers):

import numpy as np
import scipy.spatial as spatial
from collections import Counter

# Particle dictionary
num_parts = int(1e4)
particles = {'coords': np.random.rand(num_parts, 3),
             'flags': np.random.randint(0, 4, size=num_parts)}

# Object dictionary
num_objects = int(1e3)
objects_dict = {'x': [np.random.rand(1)
                      for i in range(0, num_objects)],
                'y': [np.random.rand(1)
                      for i in range(0, num_objects)],
                'z': [np.random.rand(1)
                      for i in range(0, num_objects)],
                'prop_to_calc': [np.array([])
                                 for i in range(0, num_objects)]}

# Build KDTree for particles
tree = spatial.cKDTree(particles['coords'])

# Loop through objects to calculate 'prop_to_calc' based
# on nearby particles flags within radius, r.
r = 0.1
for i in range(0, num_objects):

    # Find nearby indices of particles.
    indices = tree.query_ball_point([objects_dict['x'][i][0],
                                     objects_dict['y'][i][0],
                                     objects_dict['z'][i][0]],
                                    r)

    # Extract flags of nearby particles.
    flags_array = particles['flags'][indices]

    # Find most common flag and store that in property_to_calculate
    c = Counter(flags_array)
    objects_dict['prop_to_calc'] = np.append(objects_dict['prop_to_calc'],
                                             c.most_common(1)[0][0])

There are two data sets particles and objects_dict. I want to calculate objects_dict['prop_to_dict'] by searching nearby particles within radius, r and finding their most common flag. This is done with cKDTree and query_ball_point.

For these numbers the time is:
10 loops, best of 3: 55.8 ms per loop in Ipython 4.2.0

However, I want num_parts=1e6 and num_objects=1e5, which results in some serious slow down.

My question:

As it is CPU heavy, I want to try to parallelise it to get some speed up.

I have looked at both multiprocessing and multi threading. However the docs confuse me quite a lot, and I'm not sure how to apply the examples to this problem.

Specifically, I'm concerned with how I share both dictionarys between processes and write into objects_dict at the end.

Thanks for the help in advance.

Body:
Try to split the code and make local lists and dictionaries. Union the dictionaries and lists at the end. Just import threading and make a class CalculationThread with subclass threading.Thread and write the parallel code in the method run of the class and start the thread by thread = CalculationThread() and thread.start()

The final code for this is:

import threading

class CalculationThread(threading Tread):
    def __init__(self, range):
        self.range = range
        # use this copy instead for the thread
        self.objects_dict = dict(objects_dict)
    def run(self):
        for i in self.range:
            # your code

threads = []
threadCount = 8

lastThreadStart = num_objects
tLen = num_objects // threadCount
for i in reversed(range(threadCount)):
    threadStart = i*tLen
    t = CalculationThread(range(threadStart, lastThreadStart))
    lastThreadStart = threadStart

# wait for all to finish
for t in threads: t.join()

# code to union all objects_dicts comes here


问:
laravel 5.4 undefined variable in view
I'm kind of new to laravel and trying to pull data from a database but keep hitting an error page saying there's an undefined variable within the view.

I'm supposing there's something I'm doing wrong (or not doing) within the controller. So I have a create.blade.php that posts data from a form to the database and everything works fine, however I want it such that after posting to the database to redirect to the show.blade.php showing the uploaded data and here is where I hit a brick wall with the error messages.

This is my store function within the controller -

```<code>public function store(Request $request)
    {
     $data4page = new Data4page;

     $data4page->h1Ttle = $request->h1Ttle;
     $data4page->h4Ttle = $request->h4Ttle;
     $data4page->description = $request->description;
     $data4page->save();

     /*redirecting to the content's show page*/
     return redirect()->route('content.show', $data4page->id);
}
</code>```

And this is the show function within the same controller -

```<code>public function show($id)
    {
        //
        $data4page = Data4page::find($id);
        return view('digital.show')->with(compact('data4page'));
    }
</code>```

The error message I'm getting is -

```<code>Undefined variable: data4page (View: /var/www/html/theproject/resources/views/content/show.blade.php)
</code>```

And in the show.blade.php this is a sample of what I have -

```<code><h1>{{ $data4page->h4Ttle }}</h1>
<p>{{ $data4page->description }}</p>
<h4>{{ $data4page->h4Ttle }}</h4>
</code>```

Having said all that, I have also tried various means of returning the view within the show function of the controller but all these result in the same error message above. These variants include -

```<code>return view('content.show')->with('data4page', $data4page);
return view('content.show',['data4page'=>$data4page]);
</code>```

Update: I earlier had typos but now the error I get is -

```<code>undefined variable: {"id":9,"h1Ttle":"h1 sample text","h4Ttle":"h4 sample text","description":"body text goes here"} (View: /var/www/html/theproject/resources/views/content/show.blade.php)
</code>```

This is the show.blade.php -

```<code>@extends('main')
@section('title')
@section('content')
      <div class="app-template">
         <main class="wrapperMain">
            <div class="">
               <aside class="navSidebar">
                  <nav class="navProperty">
                     <h1 class="navProperty-title">{{ $data4page->h1Ttle }}</h1>
                  </nav>
                  <footer class="footerProperty">
                     <div class="upcomingSchedule">
                        <h4 class="upcomingSchedule-heading">{{ $data4page->h4Ttle }}</h4>
                     </div>
                  </footer>
               </aside>
            </div>
            <div class="content content--withSidebar">
               <div class="lead--Home">
                  <p>{{ $data4page->description }}</p>
               </div>
            </div>
         </main>
@endsection
</code>```

答:
You have a name mismatch.

```<code>return view('content.show')->with(['name' => $data4page]);
</code>```

Here you should use:

```<code><h1>{{ $name->h4Ttle }}</h1>
</code>```

As you called it name

In your other options you defined Data4page and in your view you use data4page (lower case d).

Title: laravel 5.4 undefined variable in view

Body:
I'm kind of new to laravel and trying to pull data from a database but keep hitting an error page saying there's an undefined variable within the view.

I'm supposing there's something I'm doing wrong (or not doing) within the controller. So I have a create.blade.php that posts data from a form to the database and everything works fine, however I want it such that after posting to the database to redirect to the show.blade.php showing the uploaded data and here is where I hit a brick wall with the error messages.

This is my store function within the controller -

public function store(Request $request)
    {
     $data4page = new Data4page;

     $data4page->h1Ttle = $request->h1Ttle;
     $data4page->h4Ttle = $request->h4Ttle;
     $data4page->description = $request->description;
     $data4page->save();

     /*redirecting to the content's show page*/
     return redirect()->route('content.show', $data4page->id);
}

And this is the show function within the same controller -

public function show($id)
    {
        //
        $data4page = Data4page::find($id);
        return view('digital.show')->with(compact('data4page'));
    }

The error message I'm getting is -

Undefined variable: data4page (View: /var/www/html/theproject/resources/views/content/show.blade.php)

And in the show.blade.php this is a sample of what I have -

{{ $data4page->h4Ttle }}

{{ $data4page->description }}

{{ $data4page->h4Ttle }}

Having said all that, I have also tried various means of returning the view within the show function of the controller but all these result in the same error message above. These variants include -

return view('content.show')->with('data4page', $data4page);
return view('content.show',['data4page'=>$data4page]);

Update: I earlier had typos but now the error I get is -

undefined variable: {"id":9,"h1Ttle":"h1 sample text","h4Ttle":"h4 sample text","description":"body text goes here"} (View: /var/www/html/theproject/resources/views/content/show.blade.php)

This is the show.blade.php -

@extends('main')
@section('title')
@section('content')

{{ $data4page->h1Ttle }}

{{ $data4page->h4Ttle }}

{{ $data4page->description }}

@endsection

Body:
You have a name mismatch.

return view('content.show')->with(['name' => $data4page]);

Here you should use:

<h1>{{ $name->h4Ttle }}</h1>

As you called it name

In your other options you defined Data4page and in your view you use data4page (lower case d).


问:
Create a list of matrices given initial list and specific transformation in R
I have a list of length 200 mylist, where each element is an integer list.

Then I want to create a table for each element, and eventually create a list with the very same length, where each element is a matrix.

Let's say for the sake of simplicity that my list is mylist = c(1001:1200).

now I want to create a transformation for each element, for example:
given that

```<code>set.seed(222)
a =  sample( length(temp), 10 )
b =  sample( length(temp), 10 )
c =  211
</code>```

where a and b are lists of length 10, I want to apply

```<code>(a * mylist[i] + b) %% c
</code>```

in  each element (out of 200) for my original list

I tried using two for loops but it does not do the job.

```<code>temp <- vector(mode='array', length =1)

for (i in 1:length(mylist) ) {
  for (j in 1:10) {
    temp[[i]] =( a[j] * mylist[[i]] + b[j] ) %% c
  }
}
</code>```

particularly I get a list of length 200, where for each element of mylist (1:200) I get result from the following transformation

```<code> (a[10]*mylist[[1]]+b[10])%%c
 (a[10]*mylist[[2]]+b[10])%%c
</code>```

...

etc, meaning that it takes into consideration only the last (out of 10) elements of lists a and b. (it is like for (j in 1:10) is not running, but takes j=10

Any idea how to implement that?

答:
In your code you are only defining the element i of temp. That's why you only obtain the last value, because it re-writes. Try this:

```<code> temp <- array(NA, c(length(mylist),10))

 for (i in 1:length(mylist) ) {
   for (j in 1:10) {
     temp[[i,j]] =( a[j] * mylist[[i]] + b[j] ) %% c
   }
 }
</code>```

Body:
I have a list of length 200 mylist, where each element is an integer list.

Then I want to create a table for each element, and eventually create a list with the very same length, where each element is a matrix.

Let's say for the sake of simplicity that my list is mylist = c(1001:1200).

now I want to create a transformation for each element, for example:
given that

set.seed(222)
a =  sample( length(temp), 10 )
b =  sample( length(temp), 10 )
c =  211

where a and b are lists of length 10, I want to apply

(a * mylist[i] + b) %% c

in  each element (out of 200) for my original list

I tried using two for loops but it does not do the job.

temp <- vector(mode='array', length =1)

for (i in 1:length(mylist) ) {
  for (j in 1:10) {
    temp[[i]] =( a[j] * mylist[[i]] + b[j] ) %% c
  }
}

particularly I get a list of length 200, where for each element of mylist (1:200) I get result from the following transformation

 (a[10]*mylist[[1]]+b[10])%%c
 (a[10]*mylist[[2]]+b[10])%%c

...

etc, meaning that it takes into consideration only the last (out of 10) elements of lists a and b. (it is like for (j in 1:10) is not running, but takes j=10

Any idea how to implement that?

Body:
In your code you are only defining the element i of temp. That's why you only obtain the last value, because it re-writes. Try this:

 temp <- array(NA, c(length(mylist),10))

 for (i in 1:length(mylist) ) {
   for (j in 1:10) {
     temp[[i,j]] =( a[j] * mylist[[i]] + b[j] ) %% c
   }
 }