问:
Remove extra = (equals to ) symbol from raw email content (which are not user inputs)
I have a java function which reads a raw email content and parses it to get the text content. The emails I send from outlook contains these extra = symbols.

What is Lorem Ipsum?

Lorem Ipsum is simply dummy text of the printing and typesetting
  industry. = Lorem Ipsum has been the industry's standard dummy text
  ever since the 1500= s, when an unknown printer took a galley of type
  and scrambled it to make a=

Something like this. How can I get the email content without these ?

```<code>private static String getTextFromMessage(MimeMessage message) throws IOException, MessagingException {
        StringWriter writer = new StringWriter();
        IOUtils.copy(message.getInputStream(), writer, "UTF-8");
        String s = writer.toString();
        return s;

}
</code>```

I am not looking for how to remove = from a normal string. I want to remove the extra characters added by outlook and retain the user input string as it is

答:
It is highly recommended that you go through the string manipulation concepts first, before asking questions that are actually quite simple.

You can use replace like this:

```<code>String s = writer.toString();

s = s.replace("=", "");

return s;
</code>```

Body:
I have a java function which reads a raw email content and parses it to get the text content. The emails I send from outlook contains these extra = symbols.

What is Lorem Ipsum?

Lorem Ipsum is simply dummy text of the printing and typesetting
  industry. = Lorem Ipsum has been the industry's standard dummy text
  ever since the 1500= s, when an unknown printer took a galley of type
  and scrambled it to make a=

Something like this. How can I get the email content without these ?

private static String getTextFromMessage(MimeMessage message) throws IOException, MessagingException {
        StringWriter writer = new StringWriter();
        IOUtils.copy(message.getInputStream(), writer, "UTF-8");
        String s = writer.toString();
        return s;

}

I am not looking for how to remove = from a normal string. I want to remove the extra characters added by outlook and retain the user input string as it is

Body:
It is highly recommended that you go through the string manipulation concepts first, before asking questions that are actually quite simple.

You can use replace like this:

String s = writer.toString();

s = s.replace("=", "");

return s;


来源: stackexchange

问:
Concatenate multiple rows data in single cell in a WEBI report
Need advice for a webi report in BO 4.1  Sorry about the alignment.

I have a report as follow:

Country
Agent
Customer
Products

UK
Mo
Sara
Bag

UK
Adam
Jill
Bag

UK
Tim
Kim
Shoes

UK
Tim
Kim
Bag

US
John
Sam
Belt

US
John
Sam
Bag

The result should look like:

Country
Agent
Customer
Products

Country
Agent
Customer
Products

UK
Mo
Sara
Bag

UK
Adam
Jill
Bag

UK
Tim
Kim
Shoes, Bag

US
John
Sam
Belt, Bag

I have 1 query that pull customers, products and country and another query that pulls Agent and country.  I have made Agent as my detail object associated with country.  I get following output

Country
Agent
Customer
Products

UK
Mo
Sara
Bag

UK
Adam
Jill
Bag

UK
Tim
Kim
Shoes

UK
Tim
Kim
Bag

US
John
Sam
Belt

US
John
Sam
Bag

I tried to follow instructions from
http://bi.srivatsakr.com/2011/08/converting-rows-into-single-cell-comma.html

[VAR Max Products] = Max ([Products] In [Customer])

[VAR Concat Products] = [Products]+", "+Previous(Self)

[VAR Max Concat Products]= [VAR Concat Products] Where ([Products]=[VAR Max Products])

[VAR Product] = If(IsNull(Previous([VAR Max Concat Products]));Substr([VAR Max Concat Products];1;Length([VAR Max Concat Products])-2);Substr([VAR Max Concat Products];1;Pos([VAR Max Concat Products];Previous([VAR Max Concat Products]))-3))
```

But that give me results like

Country
Agent
Customer
Products
[VAR Product]

UK
Mo
Sara
Bag
Bag

UK
Adam
Jill
Bag

UK
Tim
Kim
Shoes,
Bag, Shoes

UK
Tim
Kim
Bag

US
John
Sam
Belt
Bag, Belt

US
John
Sam
Bag

If I remove the Product Column, the result is as follows:

Country
Agent
Customer
Products
[VAR Product]

UK
Mo
Sara
Bag

UK
Adam
Jill

UK
Tim
Kim

UK
Tim
Kim

US
John
Sam

US
John
Sam

I can hide the Product Column but it still won't show the correct result.
Need some advice. Appreciate the help in advance.

答:
I converted some rows into a string based on this SAP blog post like this:

```<code>_Concat_MyField = Previous(Self) + (If IsNull(Previous(Self)) Then "" Else ", ") + [MyField]

Final = Last([_Concat_MyField] ForEach ([MyField]))
</code>```

The _Concat_MyField variable joins each row with the previous row's value, and the Final variable grabs the last entry, which is the one where all the rows have been joined into the string.

It makes more sense if you put [MyField] and [_Concat_MyField] into the same table in a sample report.

ContentLicense: CC BY-SA 4.0

Body:
Need advice for a webi report in BO 4.1  Sorry about the alignment.

I have a report as follow:

Country
Agent
Customer
Products

UK
Mo
Sara
Bag

UK
Adam
Jill
Bag

UK
Tim
Kim
Shoes

UK
Tim
Kim
Bag

US
John
Sam
Belt

US
John
Sam
Bag

The result should look like:

Country
Agent
Customer
Products

Country
Agent
Customer
Products

UK
Mo
Sara
Bag

UK
Adam
Jill
Bag

UK
Tim
Kim
Shoes, Bag

US
John
Sam
Belt, Bag

I have 1 query that pull customers, products and country and another query that pulls Agent and country.  I have made Agent as my detail object associated with country.  I get following output

Country
Agent
Customer
Products

UK
Mo
Sara
Bag

UK
Adam
Jill
Bag

UK
Tim
Kim
Shoes

UK
Tim
Kim
Bag

US
John
Sam
Belt

US
John
Sam
Bag

I tried to follow instructions from
http://bi.srivatsakr.com/2011/08/converting-rows-into-single-cell-comma.html

[VAR Max Products] = Max ([Products] In [Customer])

[VAR Concat Products] = [Products]+", "+Previous(Self)

[VAR Max Concat Products]= [VAR Concat Products] Where ([Products]=[VAR Max Products])

[VAR Product] = If(IsNull(Previous([VAR Max Concat Products]));Substr([VAR Max Concat Products];1;Length([VAR Max Concat Products])-2);Substr([VAR Max Concat Products];1;Pos([VAR Max Concat Products];Previous([VAR Max Concat Products]))-3))

But that give me results like

Country
Agent
Customer
Products
[VAR Product]

UK
Mo
Sara
Bag
Bag

UK
Adam
Jill
Bag

UK
Tim
Kim
Shoes,
Bag, Shoes

UK
Tim
Kim
Bag

US
John
Sam
Belt
Bag, Belt

US
John
Sam
Bag

If I remove the Product Column, the result is as follows:

Country
Agent
Customer
Products
[VAR Product]

UK
Mo
Sara
Bag

UK
Adam
Jill

UK
Tim
Kim

UK
Tim
Kim

US
John
Sam

US
John
Sam

I can hide the Product Column but it still won't show the correct result.
Need some advice. Appreciate the help in advance.

Body:
I converted some rows into a string based on this SAP blog post like this:

_Concat_MyField = Previous(Self) + (If IsNull(Previous(Self)) Then "" Else ", ") + [MyField]

Final = Last([_Concat_MyField] ForEach ([MyField]))

The _Concat_MyField variable joins each row with the previous row's value, and the Final variable grabs the last entry, which is the one where all the rows have been joined into the string.

It makes more sense if you put [MyField] and [_Concat_MyField] into the same table in a sample report.

ContentLicense: CC BY-SA 3.0


问:
python simple iteration
i would like to ask what is the best way to make simple iteration. suppose i want to repeat certain task 1000 times, which one of the following is the best? or is there a better way?

```<code>for i in range(1000):
    do something with no reference to i

i = 0
while i < 1000:
    do something with no reference to i
    i += 1
</code>```

thanks very much

答: first. because the integer is done in the internal layer rather than interpretor. Also one less global variable. </p>

ContentLicense: CC BY-SA 2.5

Title: python simple iteration

Body:
i would like to ask what is the best way to make simple iteration. suppose i want to repeat certain task 1000 times, which one of the following is the best? or is there a better way?

for i in range(1000):
    do something with no reference to i

i = 0
while i < 1000:
    do something with no reference to i
    i += 1

thanks very much


问:
Separate functions from the same class in multiple files
Is it a good practice to separate the functions of the same class in multiple .cpp files or all the functions should be in the same file?

For example:

foobar.h

```<code>#ifndef FOOBAR_H
#define FOOBAR_H

#include <QDebug>

class FooBar
{
public:
    FooBar();

    void foo();
    void bar();
};

#endif // FOOBAR_H
</code>```

foobar.cpp

```<code>#include "foobar.h"

FooBar::FooBar()
{
    qDebug() << "Constructor";
}
</code>```

foo.cpp

```<code>#include "foobar.h"

void FooBar::foo()
{
    qDebug() << "Foo";
}
</code>```

bar.cpp

```<code>#include "foobar.h"

void FooBar::bar()
{
    qDebug() << "Bar";
}
</code>```

Note: I only added the Qt tag because the example was generated in Qt, but this is a C++ related question.

答:
It depends on the size of the code of the functions, I personally when the size of the code is little I prefer to have it all in a single .h file:

foobar.h

```<code>#ifndef FOOBAR_H
#define FOOBAR_H

#include <QDebug>

class FooBar {
public:
    FooBar() {
        qDebug() << "Constructor";
    }

    void foo() {
        qDebug() << "Foo";
    }

    void bar() {
        qDebug() << "Bar";
    }
};

#endif // FOOBAR_H
</code>```

Body:
Is it a good practice to separate the functions of the same class in multiple .cpp files or all the functions should be in the same file?

For example:

foobar.h

#ifndef FOOBAR_H
#define FOOBAR_H

#include <QDebug>

class FooBar
{
public:
    FooBar();

    void foo();
    void bar();
};

#endif // FOOBAR_H

foobar.cpp

#include "foobar.h"

FooBar::FooBar()
{
    qDebug() << "Constructor";
}

foo.cpp

#include "foobar.h"

void FooBar::foo()
{
    qDebug() << "Foo";
}

bar.cpp

#include "foobar.h"

void FooBar::bar()
{
    qDebug() << "Bar";
}

Note: I only added the Qt tag because the example was generated in Qt, but this is a C++ related question.

Body:
It depends on the size of the code of the functions, I personally when the size of the code is little I prefer to have it all in a single .h file:

foobar.h

#ifndef FOOBAR_H
#define FOOBAR_H

#include <QDebug>

class FooBar {
public:
    FooBar() {
        qDebug() << "Constructor";
    }

    void foo() {
        qDebug() << "Foo";
    }

    void bar() {
        qDebug() << "Bar";
    }
};

#endif // FOOBAR_H


问:
How to create left navigation drawer when top header logo is fixed and menu item is scrolling and show in category title?
I am new in android so please guide me How to create left navigation drawer when top header logo is fixed and  menu item is scrolling and show in category title exact like this

I am trying this code

XML FIle is

My Navigation drawer is here - nav_header_main.xml and

menu file is in res/menu/

```<code> <?xml version="1.0" encoding="utf-8"?>
 <menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:title="Main Category"></item>
    <item
        android:id="@+id/nav_camera"
        android:icon="@drawable/ic_menu_camera"
        android:title="Import" />
    <item
        android:id="@+id/nav_gallery"
        android:icon="@drawable/ic_menu_gallery"
        android:title="Gallery" />
    <item
        android:id="@+id/nav_slideshow"
        android:icon="@drawable/ic_menu_slideshow"
        android:title="Slideshow" />
    <item
        android:id="@+id/nav_manage"
        android:icon="@drawable/ic_menu_manage"
        android:title="Tools" />

    <item android:title="Communicate">
    </item>

    <item
        android:id="@+id/nav_share"
        android:icon="@drawable/ic_menu_share"
        android:title="Share" />
    <item
        android:id="@+id/nav_send"
        android:icon="@drawable/ic_menu_send"
        android:title="Send" />

    <item
        android:id="@+id/nav_slideshow1"
        android:icon="@drawable/ic_menu_slideshow"
        android:title="Slideshow" />
    <item
        android:id="@+id/nav_manage1"
        android:icon="@drawable/ic_menu_manage"
        android:title="Tools" />

    <item android:title="App Category"></item>

    <item
        android:id="@+id/nav_gallery1"
        android:icon="@drawable/ic_menu_gallery"
        android:title="Gallery" />
    <item
        android:id="@+id/nav_slideshow2"
        android:icon="@drawable/ic_menu_slideshow"
        android:title="Slideshow" />
    <item
        android:id="@+id/nav_manage2"
        android:icon="@drawable/ic_menu_manage"
        android:title="Tools" />

</menu>
</code>```

my activity_main file is

```<code><android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="220dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        android:background="@color/colorAccent"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer"
        app:itemTextColor="@color/colorWhite"
        app:itemIconTint="@color/colorWhite"
        app:itemBackground="@drawable/drawer_item_bg"/>

</android.support.v4.widget.DrawerLayout>
</code>```

答:
You can achieve this by custom drawer. Try below link. Hope it will solve your problem.

Custom navigation drawer

In custom layout add imageview on top and then scrollview and inside scrollview all your layout. so logo will be fixed and items can scroll.

Or you can try this solutions.

Body:
I am new in android so please guide me How to create left navigation drawer when top header logo is fixed and  menu item is scrolling and show in category title exact like this

I am trying this code

XML FIle is

My Navigation drawer is here - nav_header_main.xml and

menu file is in res/menu/

 <?xml version="1.0" encoding="utf-8"?>
 <menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:title="Main Category"></item>
    <item
        android:id="@+id/nav_camera"
        android:icon="@drawable/ic_menu_camera"
        android:title="Import" />
    <item
        android:id="@+id/nav_gallery"
        android:icon="@drawable/ic_menu_gallery"
        android:title="Gallery" />
    <item
        android:id="@+id/nav_slideshow"
        android:icon="@drawable/ic_menu_slideshow"
        android:title="Slideshow" />
    <item
        android:id="@+id/nav_manage"
        android:icon="@drawable/ic_menu_manage"
        android:title="Tools" />

    <item android:title="Communicate">
    </item>

    <item
        android:id="@+id/nav_share"
        android:icon="@drawable/ic_menu_share"
        android:title="Share" />
    <item
        android:id="@+id/nav_send"
        android:icon="@drawable/ic_menu_send"
        android:title="Send" />

    <item
        android:id="@+id/nav_slideshow1"
        android:icon="@drawable/ic_menu_slideshow"
        android:title="Slideshow" />
    <item
        android:id="@+id/nav_manage1"
        android:icon="@drawable/ic_menu_manage"
        android:title="Tools" />

    <item android:title="App Category"></item>

    <item
        android:id="@+id/nav_gallery1"
        android:icon="@drawable/ic_menu_gallery"
        android:title="Gallery" />
    <item
        android:id="@+id/nav_slideshow2"
        android:icon="@drawable/ic_menu_slideshow"
        android:title="Slideshow" />
    <item
        android:id="@+id/nav_manage2"
        android:icon="@drawable/ic_menu_manage"
        android:title="Tools" />

</menu>

my activity_main file is

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="220dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        android:background="@color/colorAccent"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer"
        app:itemTextColor="@color/colorWhite"
        app:itemIconTint="@color/colorWhite"
        app:itemBackground="@drawable/drawer_item_bg"/>

</android.support.v4.widget.DrawerLayout>


问:
cakephp3- unable to post form data to controller function
I have a contact us form and user enter data and submits it. This data needs to accessed in controller function so I can send a mail to admin informing about the user request recently received.

But when I press submit button, nothing happens. Form just reloads and the contactus form (view page) is shown to the users. I don't know why the data is not getting passed to the controller function.

I'mm new to CakePHP framework and I'm using CakePHP3 for development purposes.

Here is my form:

```<code><?php echo $this->Form->create(null, ['url' => ['controller' => 'Pages', 'action' => 'contactus']]); ?>
    <div class="col-md-6">
        <?php echo $this->Form->input('fname', ['placeholder' => 'Your name.' , 'id' => 'fname', 'required' => 'required']); ?>
    </div>
    <div class="col-md-6">
        <?php echo $this->Form->input('mail', ['placeholder' => 'Your email.' , 'id' => 'mail', 'required' => 'required']); ?>
    </div>
    <div class="col-md-6">
        <?php echo $this->Form->input('subject', ['placeholder' => 'Write something.', 'id' => 'subject']); ?>
    </div>

    <div class="col-md-9">
        <?php echo $this->Form->button(__('Submit')); ?>
    </div>
<?php echo $this->Form->end(); ?>
</code>```

And my controller function is:

```<code> public function contactus()
 {
        $pages ='';
        if ($this->request->is('post'))
        {
            $pages =   $this->request->data('Contact');
        }
        $this->set(compact('pages'));
        $this->set('_serialize', ['pages']);
    }
</code>```

Can anyone tell me the mistakes I made?

答:
I think your form is submitting but not through the post method. So I would like to say you that, please make the bellow changes before submitting the form.

```<code>$pages ='';
    if ($this->request->is('post'))
    {
        echo "Request is post";die;
        $pages =   $this->request->data('Contact');
    }else{
        echo "request is not post";die;
    }
    $this->set(compact('pages'));
    $this->set('_serialize', ['pages']);
</code>```

Now check, which is printing in the display. Then I can help you further.

Remember: - fill the form, then after change the controller method, then press submit method.

Body:
I have a contact us form and user enter data and submits it. This data needs to accessed in controller function so I can send a mail to admin informing about the user request recently received.

But when I press submit button, nothing happens. Form just reloads and the contactus form (view page) is shown to the users. I don't know why the data is not getting passed to the controller function.

I'mm new to CakePHP framework and I'm using CakePHP3 for development purposes.

Here is my form:

<?php echo $this->Form->create(null, ['url' => ['controller' => 'Pages', 'action' => 'contactus']]); ?>

        <?php echo $this->Form->input('fname', ['placeholder' => 'Your name.' , 'id' => 'fname', 'required' => 'required']); ?>

        <?php echo $this->Form->input('mail', ['placeholder' => 'Your email.' , 'id' => 'mail', 'required' => 'required']); ?>

        <?php echo $this->Form->input('subject', ['placeholder' => 'Write something.', 'id' => 'subject']); ?>

        <?php echo $this->Form->button(__('Submit')); ?>

<?php echo $this->Form->end(); ?>

And my controller function is:

 public function contactus()
 {
        $pages ='';
        if ($this->request->is('post'))
        {
            $pages =   $this->request->data('Contact');
        }
        $this->set(compact('pages'));
        $this->set('_serialize', ['pages']);
    }

Can anyone tell me the mistakes I made?

Body:
I think your form is submitting but not through the post method. So I would like to say you that, please make the bellow changes before submitting the form.

$pages ='';
    if ($this->request->is('post'))
    {
        echo "Request is post";die;
        $pages =   $this->request->data('Contact');
    }else{
        echo "request is not post";die;
    }
    $this->set(compact('pages'));
    $this->set('_serialize', ['pages']);

Now check, which is printing in the display. Then I can help you further.

Remember: - fill the form, then after change the controller method, then press submit method.


问:
How to execute a very heavy process exposed as REST services from wildfly?
I have a process that processes an input file, uses 100% of the processor (uses 16 cores), and 8 GB of RAM. I currently run it directly from the console. But I need to call this process from a REST service. The service must be asynchronous, and there will be another service to consult the output of the first service called. The input files must be queued, because it can only be processed one at a time.

I use RestEasy on Wildfly.

My query is:

What architecture do you suggest to call this process?

I have these possible solutions.

Call from my EJB to JAR with Runtime. And have a queue of files in a database.

Transform my JAR into a Demon, which is constantly monitoring a directory. And they will be storing the files there. And that the demon took one by one the files according to the date of arrival.

Copy the classes in my EAR project, and call them as a simple EJB, and let wildfly manage the resources. This would also imply having a file queue in a database.

Do you have any other suggestions?

答:
Technically the solution is simple: have a rest endpoint call another Stateless EJB with @Asynchronous annotation. If you want to track the status, use some kind of Job entity, that you create (synchronously) when you receive the request, then start the async job with this Job entity as param and update it from your async task.

There is however a more conceptual problem: why do you need to invoke such long running op on your web server? With requirement like this it is going to be very difficult to scale your app, handle failover(what happens if your server crashes during processing)..

If you need to do IO or computation heavy task like this in java env, have a look at batch processing - jberet or spring batch will do the job. That way you can process your file in chunks, paralelize the compution and spread the load more evenly.  If you are doing some video processing or similiar task, consider using a dedicated machines with some kind of job queue(celery, kafka...) for that, and just let your server handle the rest layer and job monitoring.


问:
Python handling exceptions
In my program, I want to take in an input which should be a number.If the user inputs a string, however, the program returns an exception.I want the program set in such a way that the input is converted to int and then if the string is anything other than an int the program prints that "Stop writing please".Like for example:</p>

```<code>   x=input("Enter a number")
        if int(x)=?:         #This line should check whether the integer conversion is possible
        print("YES")
        else                #This line should execute if the above conversion couldn't take place
        print("Stop writing stuff")
</code>```

答:
You'll need to use try-except blocks:</p>

```<code>x=input("Enter a number")
try:
    x = int(x)    # If the int conversion fails, the program jumps to the exception
    print("YES")  # In that case, this line will not be reached
except ValueError:
    print("Stop writing stuff")
</code>```

Title: Python handling exceptions

Body:
In my program, I want to take in an input which should be a number.If the user inputs a string, however, the program returns an exception.I want the program set in such a way that the input is converted to int and then if the string is anything other than an int the program prints that "Stop writing please".Like for example:

   x=input("Enter a number")
        if int(x)=?:         #This line should check whether the integer conversion is possible
        print("YES")
        else                #This line should execute if the above conversion couldn't take place
        print("Stop writing stuff")

Body:
You'll need to use try-except blocks:

x=input("Enter a number")
try:
    x = int(x)    # If the int conversion fails, the program jumps to the exception
    print("YES")  # In that case, this line will not be reached
except ValueError:
    print("Stop writing stuff")


问:
Can't pass converted array from query using whereIn
I can't pass the first query collection converting it to array. Here is my controller

```<code>$memberfilters = MemberProfile::join('membership_histories', 'membership_histories.profile_id', '=','member_profiles.id')
        ->select('member_profiles.id','member_profiles.last_name','member_profiles.first_name','member_profiles.middle_name','member_profiles.name_ext','member_profiles.birthday','member_profiles.encoded_by')
        ->addSelect(DB::raw('membership_histories.profile_id, membership_histories.log_reason, max(membership_histories.effective_date) as date, membership_histories.membership_type, membership_histories.country_name, membership_histories.sub_region_name'))
        ->orderBy('member_profiles.last_name','ASC')
        ->where('membership_histories.country_name', 'Philippines')
        ->groupBy('membership_histories.profile_id')
        ->orderBy('date', 'desc')
        ->get();

    $members = MemberProfile::join('membership_histories', 'membership_histories.profile_id', '=','member_profiles.id')
        ->whereIn('member_profiles.id', $memberfilters->toArray())
        ->get();
</code>```

I will be applying more where method on the second query $members, that's why I had to pass it to there using whereIn. With this logic, I get no results '0' in my blade view

@Alexey Mezenin
When I use ->whereIn('member_profiles.id', $memberfilters->pluck('id')), I get this error

ErrorException in ComputeAge.php line 13:
  Trying to get property of non-object

This is my ComputeAge.php

```<code>namespace App\Library;
use App\MemberProfile;
use DateTime;

class ComputeAge
{
// Compute age based on given birthday.
public static function show($id)
{
    $from = new DateTime(MemberProfile::find($id)->birthday);
    $to   = new DateTime('today');
    $age = $from->diff($to)->y;

    return $age;
}
}
</code>```

答:
Use pluck(), for example:

```<code>->whereIn('member_profiles.id', $memberfilters->pluck('id')) // Or member_profiles.id instead of id
</code>```

Body:
I can't pass the first query collection converting it to array. Here is my controller

$memberfilters = MemberProfile::join('membership_histories', 'membership_histories.profile_id', '=','member_profiles.id')
        ->select('member_profiles.id','member_profiles.last_name','member_profiles.first_name','member_profiles.middle_name','member_profiles.name_ext','member_profiles.birthday','member_profiles.encoded_by')
        ->addSelect(DB::raw('membership_histories.profile_id, membership_histories.log_reason, max(membership_histories.effective_date) as date, membership_histories.membership_type, membership_histories.country_name, membership_histories.sub_region_name'))
        ->orderBy('member_profiles.last_name','ASC')
        ->where('membership_histories.country_name', 'Philippines')
        ->groupBy('membership_histories.profile_id')
        ->orderBy('date', 'desc')
        ->get();

    $members = MemberProfile::join('membership_histories', 'membership_histories.profile_id', '=','member_profiles.id')
        ->whereIn('member_profiles.id', $memberfilters->toArray())
        ->get();

I will be applying more where method on the second query $members, that's why I had to pass it to there using whereIn. With this logic, I get no results '0' in my blade view

@Alexey Mezenin
When I use ->whereIn('member_profiles.id', $memberfilters->pluck('id')), I get this error

ErrorException in ComputeAge.php line 13:
  Trying to get property of non-object

This is my ComputeAge.php

namespace App\Library;
use App\MemberProfile;
use DateTime;

class ComputeAge
{
// Compute age based on given birthday.
public static function show($id)
{
    $from = new DateTime(MemberProfile::find($id)->birthday);
    $to   = new DateTime('today');
    $age = $from->diff($to)->y;

    return $age;
}
}

Body:
Use pluck(), for example:

->whereIn('member_profiles.id', $memberfilters->pluck('id')) // Or member_profiles.id instead of id


答:
The for loop is more concise and more readable. while loops are rarely used in Python (with the exception of while True).

A bit of idiomatic Python: if you're trying to do something a set number of times with a range (with no need to use the counter), it's good practice to name the counter _. Example:

```<code>for _ in range(1000):
    # do something 1000 times
</code>```

Title: python simple iteration

Body:
The for loop is more concise and more readable. while loops are rarely used in Python (with the exception of while True).

A bit of idiomatic Python: if you're trying to do something a set number of times with a range (with no need to use the counter), it's good practice to name the counter _. Example:

for _ in range(1000):
    # do something 1000 times


问:
Is kinit required while accessing a Kerberized service through Java code?
I have a java application which needs to access Hadoop cluster to fetch a file at regular intervals(say, every 24 hours).

Since Kerberos protocol is enabled for protection on that cluster, I am using loginUserFromKeytab() method of UserGroupInformation class : https://hadoop.apache.org/docs/r1.2.1/api/org/apache/hadoop/security/UserGroupInformation.html.

Now, I know that kinit command grants a ticket-granting ticket to access any Kerberized service and this ticket has to be refreshed periodically(through kinit command). Now, my question is, is it required to run kinit periodically(from code) in combination with the above Java API for the code to work? Or will running it once be sufficient? Or is it not required at all.

Thanks for reading.

答:
No. you don't need to run kinit periodically from anywhere if you are using the function loginUserFromKeytab with a valid keytab and username.

From docs

Log a user in from a keytab file. Loads a user identity from a keytab file and logs them in. They become the currently logged-in user.

So everytime you call the method loginUserFromKeytab with valid parameters. It logs in the user.


问:
How do I change NA into Column median
A data frame contains 123 columns,
and each columns have at least 1 NA value.

I want these NA values to be raplaced into column median.
because there are so many columns, i cannot write a code using each column name.

so i tried to use 'apply' to solve this but it didn't work.

```<code>data2[-1]<-lapply(data2[-1],function(x)x - median(x,na.rm=TRUE))
</code>```

it says it doesn't work since it is data frame, not numeric.

答:
```<code>for(i in 1:ncol(df)){
  df[is.na(df[,i]), i] <- median(df[,i], na.rm = TRUE)
}
</code>```

Title: How do I change NA into Column median

Body:
A data frame contains 123 columns,
and each columns have at least 1 NA value.

I want these NA values to be raplaced into column median.
because there are so many columns, i cannot write a code using each column name.

so i tried to use 'apply' to solve this but it didn't work.

data2[-1]<-lapply(data2[-1],function(x)x - median(x,na.rm=TRUE))

it says it doesn't work since it is data frame, not numeric.


答:
We can use na.aggregate

```<code> library(zoo)
 j1 <- sapply(df1, is.numeric)
 df1[j1] <- na.aggregate(df1[j1], FUN = median)
</code>```

Title: How do I change NA into Column median

Body:
We can use na.aggregate

 library(zoo)
 j1 <- sapply(df1, is.numeric)
 df1[j1] <- na.aggregate(df1[j1], FUN = median)


问:
Creating different matrices from data frame with R for loop
I've got 2 data frames (df 1 and 2) that have the following structure:

```<code>CHR SNP A1 A2 FAM CA1 CA2
1 rs3818361 A G 0.35 7 13
2 rs7561528 A G 0.2 4 16
2 rs6733839 T C 0.45 9 11
2 rs744373 G A 0.45 9 11
2 rs35349669 T C 0.35 7 13
...
</code>```

They have 7 columns and 41 number of rows (without counting the colnames row). With the columns CA1 and CA2 of each one of the data frames I have to build 2x2 matrices, like this:

```<code>[CA1 from df1] [CA2 from df1] #first row CA1 and CA2 from df1
[CA1 from df2] [CA2 from df2] #first row CA1 and CA2 from df2

[CA1 from df1] [CA2 from df1] #second row CA1 and CA2 from df1
[CA1 from df2] [CA2 from df2] #second row CA1 and CA2 from df2

[CA1 from df1] [CA2 from df1] #third row CA1 and CA2 from df1
[CA1 from df2] [CA2 from df2] #third row CA1 and CA2 from df2
</code>```

I thought about a for loop for (i in 1:41), but i'm having trouble to consolidate the idea.

```<code>for (i in 1:41) {
do
datai <- c(df1[i,7],df1[i,8],df2[i,7],df2[i,8])
matrixi <- matrix(datai, nrow=2, ncol=2, byrow=TRUE)
}
</code>```

I want the loop to generate 41 matrices. The "i" that i put at matrix and data (datai and matrixi) mean "i want 41 of these". Any thoughts?

答:
```<code>var <- c("CA1", "CA2")
lapply(seq(nrow(df1)), function(x) rbind(df1[x,var], df2[x,var]))
</code>```

Body:
I've got 2 data frames (df 1 and 2) that have the following structure:

CHR SNP A1 A2 FAM CA1 CA2
1 rs3818361 A G 0.35 7 13
2 rs7561528 A G 0.2 4 16
2 rs6733839 T C 0.45 9 11
2 rs744373 G A 0.45 9 11
2 rs35349669 T C 0.35 7 13
...

They have 7 columns and 41 number of rows (without counting the colnames row). With the columns CA1 and CA2 of each one of the data frames I have to build 2x2 matrices, like this:

[CA1 from df1] [CA2 from df1] #first row CA1 and CA2 from df1
[CA1 from df2] [CA2 from df2] #first row CA1 and CA2 from df2

[CA1 from df1] [CA2 from df1] #second row CA1 and CA2 from df1
[CA1 from df2] [CA2 from df2] #second row CA1 and CA2 from df2

[CA1 from df1] [CA2 from df1] #third row CA1 and CA2 from df1
[CA1 from df2] [CA2 from df2] #third row CA1 and CA2 from df2

I thought about a for loop for (i in 1:41), but i'm having trouble to consolidate the idea.

for (i in 1:41) {
do
datai <- c(df1[i,7],df1[i,8],df2[i,7],df2[i,8])
matrixi <- matrix(datai, nrow=2, ncol=2, byrow=TRUE)
}

I want the loop to generate 41 matrices. The "i" that i put at matrix and data (datai and matrixi) mean "i want 41 of these". Any thoughts?


答: The first is considered idiomatic. In Python 2.x, use xrange instead of range.

Title: python simple iteration


问:
Django, how to update DB based on the foreignkey value?
I have tried in Models (with "def save") but give me error "int() argument must be a string, a bytes-like object or a number, not 'Length'".

I have fields "length" and "width" in foreignkey. And I want when submit a form to add value of "squaremeter" field to DB calculated based on the length and width selected

```<code>def save(self, *args, **kwargs):
        self.squaremeter = self.length * self.width
        self.squaremeter.save()
        super(Product, self).save(*args, **kwargs)
</code>```

For two weeks I'm stuck in this issue

Update:

```<code>class Product(models.Model):
    length      = models.ForeignKey(Length, on_delete=models.SET_NULL, null=True, blank=True)
    width       = models.ForeignKey(Width, on_delete=models.SET_NULL, null=True, blank=True)
    squaremeter = models.DecimalField(max_digits=6, decimal_places=4, blank=True)
</code>```

Update2:

```<code>class Length(models.Model):
    value    = models.PositiveSmallIntegerField(unique=True)

class Width(models.Model):
    value    = models.PositiveSmallIntegerField(unique=True)
</code>```

答:
Edit your save method like this,</p>

```<code>def save(self, *args, **kwargs):
    self.squaremeter = self.length.value * self.width.value
    super(Product, self).save(*args, **kwargs)
</code>```

Body:
I have tried in Models (with "def save") but give me error "int() argument must be a string, a bytes-like object or a number, not 'Length'".

I have fields "length" and "width" in foreignkey. And I want when submit a form to add value of "squaremeter" field to DB calculated based on the length and width selected

def save(self, *args, **kwargs):
        self.squaremeter = self.length * self.width
        self.squaremeter.save()
        super(Product, self).save(*args, **kwargs)

For two weeks I'm stuck in this issue

Update:

class Product(models.Model):
    length      = models.ForeignKey(Length, on_delete=models.SET_NULL, null=True, blank=True)
    width       = models.ForeignKey(Width, on_delete=models.SET_NULL, null=True, blank=True)
    squaremeter = models.DecimalField(max_digits=6, decimal_places=4, blank=True)

Update2:

class Length(models.Model):
    value    = models.PositiveSmallIntegerField(unique=True)

class Width(models.Model):
    value    = models.PositiveSmallIntegerField(unique=True)

Body:
Edit your save method like this,

def save(self, *args, **kwargs):
    self.squaremeter = self.length.value * self.width.value
    super(Product, self).save(*args, **kwargs)


答:
You can simply use a try-except block to catch the exceptional case, and inside there, print your statement. Something like this:</p>

```<code>x=input("Enter a number")
try:
    x=int(x)
    print("YES")
except:
    print("Stop writing stuff")
</code>```

Title: Python handling exceptions

Body:
You can simply use a try-except block to catch the exceptional case, and inside there, print your statement. Something like this:

x=input("Enter a number")
try:
    x=int(x)
    print("YES")
except:
    print("Stop writing stuff")


问:
Query regarding JNI Implementation
We have a service in Java which use JNI to invoke a method written in C++. I have few questions on how the method in C++ is invoked.
1) Can anyone describe briefly on how the JNI architecture works(Thing i am looking in particular are What happens when C++ method is called? Who will execute the method? What happens after the method returns? Who will allocate the memory to the method? Where will the memory gets allotted? How is the allotted memory released from RAM, Who will release the memory, When will the memory gets released) </p>

答:
If you are looking for a simple description, take a look here:

http://jnicookbook.owsiak.org/recipe-No-001/

If you are looking for more detailed description, take a look here:

https://www.safaribooksonline.com/library/view/javatm-native-interface/0201325772/

If you are looking for more technical details, check the specification here:

http://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/jniTOC.html

Have fun with JNI!

Title: Query regarding JNI Implementation


问:
Loading map pins from firebase onto mapkit in swift for all users to be able to see
Im creating a tagging app, where a user can tag street art to a map, this information is then available for all users to see.

I can upload my data to Firebase however Im struggling being able to pull this data back down to appear on the map as an annotation.

Firebase Data Structure

I have created a loadCustomAnnotations() to load up the database information as a pin on my map, I know I need to observe the values and just load in the "art" path, and loop over all the results however I cant seem to turn this into an annotation! can anyone help?! thanks.

```<code>func loadCustomLocations() {

    FIRDatabase.database().reference(withPath: "art")

    let artPin = FIRDatabase.database().reference(withPath: "art")

    artPin.observe(.value, with: { snapshot in

        for item in snapshot.children {
            guard let snapshot = item as? FIRDataSnapshot else { continue }

            let ref = art(snapshot: snapshot)

            print(snapshot)

            self.artDrops.append(ref)

     //       self.makeAnnotation(artDrops: art)

        }
    })
}
</code>```

}

this function now prints all my locations i just need to know how to turn this into an annotation!

Printing Locations

答:
As soon as you are now able to upload and get back all you locations, the following steps won't be so hard. Just using .addAnnotations and you are good to go!</p>

```<code>let artAnnotation = MKPointAnnotation()
            var artDrops = [CLLocation]()
            for location in artDrops{
            artAnnotation.coordinate = location.coordinate
            artAnnotation.title = "your location title"
            mapView.addAnnotations([artAnnotation])
            }
</code>```

Body:
Im creating a tagging app, where a user can tag street art to a map, this information is then available for all users to see.

I can upload my data to Firebase however Im struggling being able to pull this data back down to appear on the map as an annotation.

Firebase Data Structure

I have created a loadCustomAnnotations() to load up the database information as a pin on my map, I know I need to observe the values and just load in the "art" path, and loop over all the results however I cant seem to turn this into an annotation! can anyone help?! thanks.

func loadCustomLocations() {

    FIRDatabase.database().reference(withPath: "art")

    let artPin = FIRDatabase.database().reference(withPath: "art")

    artPin.observe(.value, with: { snapshot in

        for item in snapshot.children {
            guard let snapshot = item as? FIRDataSnapshot else { continue }

            let ref = art(snapshot: snapshot)

            print(snapshot)

            self.artDrops.append(ref)

     //       self.makeAnnotation(artDrops: art)

        }
    })
}

}

this function now prints all my locations i just need to know how to turn this into an annotation!

Printing Locations

Body:
As soon as you are now able to upload and get back all you locations, the following steps won't be so hard. Just using .addAnnotations and you are good to go!

let artAnnotation = MKPointAnnotation()
            var artDrops = [CLLocation]()
            for location in artDrops{
            artAnnotation.coordinate = location.coordinate
            artAnnotation.title = "your location title"
            mapView.addAnnotations([artAnnotation])
            }


问:
How to include layout inside layout?
How to include layout inside layout in Android?

I am creating common layout. I want to include that layout in another page.

答:
From Official documents about Re-using Layouts

Although Android offers a variety of widgets to provide small and
  re-usable interactive elements, you might also need to re-use larger
  components that require a special layout. To efficiently re-use
  complete layouts, you can use the  tag to embed another
  layout inside the current layout.

Here is my header.xml file which i can reuse using include tag

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF"
    >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:gravity="center"
        android:text="@string/app_name"
        android:textColor="#000000" />

</RelativeLayout>
</code>```

No I use the  tag in XML to add another layout from another XML file.

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#f0f0f0" >

    <include
        android:id="@+id/header_VIEW"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        layout="@layout/header" />

        <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:background="#ffffff"
        android:orientation="vertical"
        android:padding="5dp" >

    </LinearLayout>
</code>```

Title: How to include layout inside layout?

Body:
From Official documents about Re-using Layouts

Although Android offers a variety of widgets to provide small and
  re-usable interactive elements, you might also need to re-use larger
  components that require a special layout. To efficiently re-use
  complete layouts, you can use the  tag to embed another
  layout inside the current layout.

Here is my header.xml file which i can reuse using include tag

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF"
    >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:gravity="center"
        android:text="@string/app_name"
        android:textColor="#000000" />

</RelativeLayout>

No I use the  tag in XML to add another layout from another XML file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#f0f0f0" >

    <include
        android:id="@+id/header_VIEW"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        layout="@layout/header" />

        <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:background="#ffffff"
        android:orientation="vertical"
        android:padding="5dp" >

    </LinearLayout>


问:
How to get relative path from UriInfo
I'm working with JAX-RS in Java.
I need to get from the UriInfo the relative path of the URI, i.e. the URI without the scheme and authority parts but with path and query parameters.
What is the best way to do it?</p>

答:
I needed the exact same thing although few years later. Nevertheless here's how.</p>

```<code>URI requestURI = this.uriInfo.getRequestUri();
URI baseUri = this.uriInfo.getBaseUri();
URI uri = baseUri.relativize(requestURI);
</code>```

Title: How to get relative path from UriInfo

Body:
I needed the exact same thing although few years later. Nevertheless here's how.

URI requestURI = this.uriInfo.getRequestUri();
URI baseUri = this.uriInfo.getBaseUri();
URI uri = baseUri.relativize(requestURI);


问:
Bootstrap Modal retains my backdrop property
In a single page I call a Bootstrap modal twice by using different button. One button display the modal that allow to close by clicking anywhere, while the other button can only be closed by clicking the Close or X button.

But if I click the click anywhere button first, then the second button can be closed by clicking anywhere too.

If I click the close by clicking close button first, then the second button can also only be closed by clicking the close button.

Here is how I call the close anywhere button:

```<code>$('#myModal').modal();
</code>```

Here is how I call the close using close button:

```<code>$('#myModal').modal({backdrop:'static',keyboard:false});
</code>```

答:
If you are using data attributes, use this for second button

```<code><button data-target="#myModal" data-toggle="modal" data-backdrop="static" data-keyboard="false">
open modal
</code>```

pass {keyboard: false} to prevent closing the modal by pressing ESC

Body:
In a single page I call a Bootstrap modal twice by using different button. One button display the modal that allow to close by clicking anywhere, while the other button can only be closed by clicking the Close or X button.

But if I click the click anywhere button first, then the second button can be closed by clicking anywhere too.

If I click the close by clicking close button first, then the second button can also only be closed by clicking the close button.

Here is how I call the close anywhere button:

$('#myModal').modal();

Here is how I call the close using close button:

$('#myModal').modal({backdrop:'static',keyboard:false});

Body:
If you are using data attributes, use this for second button

<button data-target="#myModal" data-toggle="modal" data-backdrop="static" data-keyboard="false">
open modal

pass {keyboard: false} to prevent closing the modal by pressing ESC


答:
We can use Map

```<code>Map(rbind, split(df1[c('CA1', 'CA2')], 1:nrow(df1)),
                 split(df2[c('CA1', 'CA2')], 1:nrow(df2)))
</code>```

Title: Creating different matrices from data frame with R for loop

Body:
We can use Map

Map(rbind, split(df1[c('CA1', 'CA2')], 1:nrow(df1)),
                 split(df2[c('CA1', 'CA2')], 1:nrow(df2)))


问:
Unique ID generation in MS-Excel
I need to create an unique ID in an excel sheet with the combination of values from other columns.

The ID should be like IP-(First three letters of column B)-(Random 4 digit number)-(First three letters of column D)

答:
Use this. It gives the ID no. as in your screen shot.</p>

```<code>="IP"&"_"&LEFT(UPPER(B2),3)&"_"&TEXT(ROW()-1,"0000")&"_"&LEFT(UPPER(D2),3)
</code>```

Title: Unique ID generation in MS-Excel

Body:
Use this. It gives the ID no. as in your screen shot.

="IP"&"_"&LEFT(UPPER(B2),3)&"_"&TEXT(ROW()-1,"0000")&"_"&LEFT(UPPER(D2),3)


问:
Cannot import mongodb
I tried mongo import like this

mongoimport -d test -c foo importfile.json

mongoimport --host localhost --db local --collection lecturer --type json --file temp.json --headerline --upsert

and I've got same error message "Syntax Error: missing ; before statement (shell):1"
what's wrong with my code & how to import if my data stored in C:\Documents and Settings\User\Desktop ?? please help, thank's in advance

答: Open the "Mongo/Server/3.4/bin" folder of mongo db in another command window and try again.It Will work.</p>

Title: Cannot import mongodb


问:
Node Red - external modules won't load to palette
I've installed the Particle and the arduino library with npm. In the 'Users/greg'(mac os x) I can see the node-modules folder and all the above mentioned libraries but they won't appear in the editor. I've tried 'Import-Library' but the menu is broken. Any ideas? </p>

答:
on your node-red dashboard click the triple lines in the top right

then click "Manage palette"

then click the "install" tab on the palette manager

search for your library and install it


问:
How to split a string into a fixed length string array?
I have a long string like this

```<code>dim LongString as String = "123abc456def789ghi"
</code>```

And I want to split it into a string array. Each element of the array should be in 3 characters length

For example,

```<code>Dim LongArray(5) As String
LongArray(0)  = "123"
LongArray(1)  = "abc"
LongArray(2)  = "456"
LongArray(3)  = "def"
LongArray(4)  = "789"
LongArray(5)  = "ghi"
</code>```

How do I split it using VB.net code?

答:
I have added some more logic to @jon code. This will work perfectly for the string which has length less than length passed.</p>

```<code> Public Shared Function SplitByLength(ByVal [text] As String, ByVal length As Integer) As String()

    Dim stringLength = text.Length
    Dim arrLength As Integer = ([text].Length \ length) - 1 + IIf(([text].Length
                                             Mod length) > 0, 1, 0)
    Dim strArray As String() = New String(arrLength) {}

    Dim returnString As String = ""
    Dim i As Integer
    Dim remLength As Integer = 0

    For i = 0 To strArray.Length - 1
      remLength = stringLength - i * length
      If remLength < length Then
        strArray(i) = [text].Substring((i * length), remLength)
      Else
        strArray(i) = [text].Substring((i * length), length)
      End If
    Next i

       Return  strArray
END FUNCTION
</code>```

Body:
I have a long string like this

dim LongString as String = "123abc456def789ghi"

And I want to split it into a string array. Each element of the array should be in 3 characters length

For example,

Dim LongArray(5) As String
LongArray(0)  = "123"
LongArray(1)  = "abc"
LongArray(2)  = "456"
LongArray(3)  = "def"
LongArray(4)  = "789"
LongArray(5)  = "ghi"

How do I split it using VB.net code?

Body:
I have added some more logic to @jon code. This will work perfectly for the string which has length less than length passed.

 Public Shared Function SplitByLength(ByVal [text] As String, ByVal length As Integer) As String()

    Dim stringLength = text.Length
    Dim arrLength As Integer = ([text].Length \ length) - 1 + IIf(([text].Length
                                             Mod length) > 0, 1, 0)
    Dim strArray As String() = New String(arrLength) {}

    Dim returnString As String = ""
    Dim i As Integer
    Dim remLength As Integer = 0

    For i = 0 To strArray.Length - 1
      remLength = stringLength - i * length
      If remLength < length Then
        strArray(i) = [text].Substring((i * length), remLength)
      Else
        strArray(i) = [text].Substring((i * length), length)
      End If
    Next i

       Return  strArray
END FUNCTION


问:
Check OS version in Swift?
I'm trying to check system information in Swift. I figured out, that it could be achieved by code:

```<code>var sysData:CMutablePointer<utsname> = nil
let retVal:CInt = uname(sysData)
</code>```

I have two problems with this code:

What should be sysData's initial value? This example gives -1 in retVal probably because sysData is nil.

How can I read information from sysData?

答:
Most of sample codes written here will get unexpected result with extra-zero versions. For example,

```<code>func SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(version: String) -> Bool {
return UIDevice.current.systemVersion.compare(version, options: .numeric) != ComparisonResult.orderedAscending
}
</code>```

This method won't return true with passed version "10.3.0" in iOS "10.3". This kind of result does not make sense and they must be regarded as same version. To get accurate comparison result, we must consider comparing all of number components in version string. Plus, providing global methods in all capital letters is not a good way to go. As version type we use in our SDK is a String, it's make sense that extending comparing functionality in String.

To compare system version, all of the following examples should work.

```<code>XCTAssertTrue(UIDevice.current.systemVersion.isVersion(lessThan: "99.0.0"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(equalTo: UIDevice.current.systemVersion))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(greaterThan: "3.5.99"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(lessThanOrEqualTo: "10.3.0.0.0.0.0.0"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(greaterThanOrEqualTo: "10.3"))
</code>```

You can check it out in my repository here
https://github.com/DragonCherry/VersionCompare

Title: Check OS version in Swift?

Body:
I'm trying to check system information in Swift. I figured out, that it could be achieved by code:

var sysData:CMutablePointer<utsname> = nil
let retVal:CInt = uname(sysData)

I have two problems with this code:

What should be sysData's initial value? This example gives -1 in retVal probably because sysData is nil.

How can I read information from sysData?

Body:
Most of sample codes written here will get unexpected result with extra-zero versions. For example,

func SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(version: String) -> Bool {
return UIDevice.current.systemVersion.compare(version, options: .numeric) != ComparisonResult.orderedAscending
}

This method won't return true with passed version "10.3.0" in iOS "10.3". This kind of result does not make sense and they must be regarded as same version. To get accurate comparison result, we must consider comparing all of number components in version string. Plus, providing global methods in all capital letters is not a good way to go. As version type we use in our SDK is a String, it's make sense that extending comparing functionality in String.

To compare system version, all of the following examples should work.

XCTAssertTrue(UIDevice.current.systemVersion.isVersion(lessThan: "99.0.0"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(equalTo: UIDevice.current.systemVersion))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(greaterThan: "3.5.99"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(lessThanOrEqualTo: "10.3.0.0.0.0.0.0"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(greaterThanOrEqualTo: "10.3"))

You can check it out in my repository here
https://github.com/DragonCherry/VersionCompare


问:
WRITE and READ memory mapped device registers in Linux on ARM
I am trying to read and write registers on my ARM9 (SAM9X25) following those steps : http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka3750.html
I ended with the following code :

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

#define PIO_WPMR_BANK_D                     0xFFFFFAE4  // PIO Write Protection Mode Register Bank D
#define PIO_PUER_BANK_D                     0xFFFFFA64  // PIO Pull-Up Enable Register Bank D
#define PIO_PUSR_BANK_D                     0xFFFFFA68  // PIO Pull-Up Status Register Bank D

#define MASK_LED7                           0xFFDFFFFF  // LED7 Mask
#define DESABLE_WRITE_PROTECTION_BANK_D     0x50494F00  // Desable write protection Bank D

int main(void) {
    printf("test");
    unsigned int volatile * const register_PIO_WPMR_BANK_D = (unsigned int *) PIO_WPMR_BANK_D;

    unsigned int volatile * const register_PIO_PUSR_BANK_D = (unsigned int *) PIO_PUSR_BANK_D;

    unsigned int volatile * const port_D = (unsigned int *) PIO_PUER_BANK_D;

    *register_PIO_WPMR_BANK_D = DESABLE_WRITE_PROTECTION_BANK_D;

    *port_D = *register_PIO_PUSR_BANK_D & MASK_LED7;

    return 0; }
</code>```

I cross compiled my code in Ubuntu 16.04 like so arm-linux-gnueabi-gcc gpio.c -o gpio
But I have a Segmentation Fault just after the printf during the execution of the program on my board.
 I know the addresses are right... So why do I have this error?
Is it the good way ?
Thank you for your help !

SOLUTION :

Thank you to @vlk I could make it work ! Here is a little example for toggling a LED :

```<code>#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>

#define handle_error(msg) \
           do { perror(msg); exit(EXIT_FAILURE); } while (0)

#define _PIOD_BANK_D                            0xA00

#define _PIO_OFFSET                             0xFFFFF000

/* When executing this on the board :
    long sz = sysconf(_SC_PAGESIZE);
    printf("%ld\n\r",sz);
   We have 4096.
*/
#define _MAP_SIZE                           0x1000  // 4096

#define _WPMR_OFFSET                        0x0E4   // PIO Write Protection Mode Register Bank D

#define _PIO_ENABLE                         0x000
#define _PIO_DISABLE                        0x004
#define _PIO_STATUS                         0x008
#define _OUTPUT_ENABLE                      0x010
#define _OUTPUT_DISABLE                     0x014
#define _OUTPUT_STATUS                      0x018
#define _FILTER_ENABLE                      0x020
#define _FILTER_DISABLE                     0x024
#define _FILTER_STATUS                      0x028
#define _OUTPUT_DATA_SET                    0x030
#define _OUTPUT_DATA_CLEAR                  0x034
#define _OUTPUT_DATA_STATUS                 0x038
#define _PIN_DATA_STATUS                    0x03c
#define _MULTI_DRIVER_ENABLE                0x050
#define _MULTI_DRIVER_DISABLE               0x054
#define _MULTI_DRIVER_STATUS                0x058
#define _PULL_UP_DISABLE                    0x060
#define _PULL_UP_ENABLE                     0x064
#define _PULL_UP_STATUS                     0x068
#define _PULL_DOWN_DISABLE                  0x090
#define _PULL_DOWN_ENABLE                   0x094
#define _PULL_DOWN_STATUS                   0x098

#define _DISABLE_WRITE_PROTECTION           0x50494F00  // Desable write protection

#define LED_PIN                                 21

int main(void) {

    volatile void *gpio_addr;
    volatile unsigned int *gpio_enable_addr;
    volatile unsigned int *gpio_output_mode_addr;
    volatile unsigned int *gpio_output_set_addr;
    volatile unsigned int *gpio_output_clear_addr;
    volatile unsigned int *gpio_data_status_addr;
    volatile unsigned int *gpio_write_protection_addr;

    int fd = open("/dev/mem", O_RDWR|O_SYNC);
    if (fd < 0){
        fprintf(stderr, "Unable to open port\n\r");
        exit(fd);
    }

    gpio_addr = mmap(NULL, _MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, _PIO_OFFSET);

    if(gpio_addr == MAP_FAILED){
        handle_error("mmap");
    }

    gpio_write_protection_addr = gpio_addr + _PIOD_BANK_D + _WPMR_OFFSET;

    gpio_enable_addr = gpio_addr + _PIOD_BANK_D + _PIO_ENABLE;

    gpio_output_mode_addr = gpio_addr + _PIOD_BANK_D + _OUTPUT_ENABLE;

    gpio_output_set_addr = gpio_addr + _PIOD_BANK_D + _OUTPUT_DATA_SET;

    gpio_output_clear_addr = gpio_addr + _PIOD_BANK_D + _OUTPUT_DATA_CLEAR;

    gpio_data_status_addr = gpio_addr + _PIOD_BANK_D + _OUTPUT_DATA_STATUS;

    *gpio_write_protection_addr = _DISABLE_WRITE_PROTECTION;

    *gpio_enable_addr = 1 << LED_PIN;
    *gpio_output_mode_addr = 1 << LED_PIN; // Output

    // If LED
    if((*gpio_data_status_addr & (1<<LED_PIN)) > 0){
        *gpio_output_clear_addr = 1 << LED_PIN;
    }else{
        *gpio_output_set_addr = 1 << LED_PIN;
    }

    return 0;
}
</code>```

EDIT :

Answer for the 3) in the comments. You have to change the mmap and the assignations like so if you want it to work with all the offsets (i.e : mmap example):

```<code>#define _PIO_OFFSET                         0xFFFFFA00 // Instead of 0xFFFFF000
#define _MAP_SIZE                           0x1000  // 4096
#define _MAP_MASK                           (_MAP_SIZE - 1)
#define _PA_OFFSET                          _PIO_OFFSET & ~_MAP_MASK
</code>```

And the mmap :

```<code>gpio_addr = mmap(NULL, _MAP_SIZE + _PIO_OFFSET - _PA_OFFSET, PROT_READ | PROT_WRITE, MAP_SHARED, fd, _PA_OFFSET);
</code>```

And for the assignation :

```<code>gpio_enable_addr = gpio_addr + _PIO_OFFSET - (_PA_OFFSET) + _PIO_ENABLE;
</code>```

答:
You can't access registers directly, because Linux use MMU and this create for your application virtual address space which is different than physical MCU address space and access outside this virtual address space cause segmentation fault.

Only Way to access these registers in Linux (if you don't want to write kernel drivers) is to open file /dev/mem as file and map it with mmap

For example I have small python library for access GPIO registers on Atmel SAM MCU gpiosam. You can inspire and port it to C.

Body:
I am trying to read and write registers on my ARM9 (SAM9X25) following those steps : http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka3750.html
I ended with the following code :

#include "stdio.h"

#define PIO_WPMR_BANK_D                     0xFFFFFAE4  // PIO Write Protection Mode Register Bank D
#define PIO_PUER_BANK_D                     0xFFFFFA64  // PIO Pull-Up Enable Register Bank D
#define PIO_PUSR_BANK_D                     0xFFFFFA68  // PIO Pull-Up Status Register Bank D

#define MASK_LED7                           0xFFDFFFFF  // LED7 Mask
#define DESABLE_WRITE_PROTECTION_BANK_D     0x50494F00  // Desable write protection Bank D

int main(void) {
    printf("test");
    unsigned int volatile * const register_PIO_WPMR_BANK_D = (unsigned int *) PIO_WPMR_BANK_D;

    unsigned int volatile * const register_PIO_PUSR_BANK_D = (unsigned int *) PIO_PUSR_BANK_D;

    unsigned int volatile * const port_D = (unsigned int *) PIO_PUER_BANK_D;

    *register_PIO_WPMR_BANK_D = DESABLE_WRITE_PROTECTION_BANK_D;

    *port_D = *register_PIO_PUSR_BANK_D & MASK_LED7;

    return 0; }

I cross compiled my code in Ubuntu 16.04 like so arm-linux-gnueabi-gcc gpio.c -o gpio
But I have a Segmentation Fault just after the printf during the execution of the program on my board.
 I know the addresses are right... So why do I have this error?
Is it the good way ?
Thank you for your help !

SOLUTION :

Thank you to @vlk I could make it work ! Here is a little example for toggling a LED :

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>

#define handle_error(msg) \
           do { perror(msg); exit(EXIT_FAILURE); } while (0)

#define _PIOD_BANK_D                            0xA00

#define _PIO_OFFSET                             0xFFFFF000

/* When executing this on the board :
    long sz = sysconf(_SC_PAGESIZE);
    printf("%ld\n\r",sz);
   We have 4096.
*/
#define _MAP_SIZE                           0x1000  // 4096

#define _WPMR_OFFSET                        0x0E4   // PIO Write Protection Mode Register Bank D

#define _PIO_ENABLE                         0x000
#define _PIO_DISABLE                        0x004
#define _PIO_STATUS                         0x008
#define _OUTPUT_ENABLE                      0x010
#define _OUTPUT_DISABLE                     0x014
#define _OUTPUT_STATUS                      0x018
#define _FILTER_ENABLE                      0x020
#define _FILTER_DISABLE                     0x024
#define _FILTER_STATUS                      0x028
#define _OUTPUT_DATA_SET                    0x030
#define _OUTPUT_DATA_CLEAR                  0x034
#define _OUTPUT_DATA_STATUS                 0x038
#define _PIN_DATA_STATUS                    0x03c
#define _MULTI_DRIVER_ENABLE                0x050
#define _MULTI_DRIVER_DISABLE               0x054
#define _MULTI_DRIVER_STATUS                0x058
#define _PULL_UP_DISABLE                    0x060
#define _PULL_UP_ENABLE                     0x064
#define _PULL_UP_STATUS                     0x068
#define _PULL_DOWN_DISABLE                  0x090
#define _PULL_DOWN_ENABLE                   0x094
#define _PULL_DOWN_STATUS                   0x098

#define _DISABLE_WRITE_PROTECTION           0x50494F00  // Desable write protection

#define LED_PIN                                 21

int main(void) {

    volatile void *gpio_addr;
    volatile unsigned int *gpio_enable_addr;
    volatile unsigned int *gpio_output_mode_addr;
    volatile unsigned int *gpio_output_set_addr;
    volatile unsigned int *gpio_output_clear_addr;
    volatile unsigned int *gpio_data_status_addr;
    volatile unsigned int *gpio_write_protection_addr;

    int fd = open("/dev/mem", O_RDWR|O_SYNC);
    if (fd < 0){
        fprintf(stderr, "Unable to open port\n\r");
        exit(fd);
    }

    gpio_addr = mmap(NULL, _MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, _PIO_OFFSET);

    if(gpio_addr == MAP_FAILED){
        handle_error("mmap");
    }

    gpio_write_protection_addr = gpio_addr + _PIOD_BANK_D + _WPMR_OFFSET;

    gpio_enable_addr = gpio_addr + _PIOD_BANK_D + _PIO_ENABLE;

    gpio_output_mode_addr = gpio_addr + _PIOD_BANK_D + _OUTPUT_ENABLE;

    gpio_output_set_addr = gpio_addr + _PIOD_BANK_D + _OUTPUT_DATA_SET;

    gpio_output_clear_addr = gpio_addr + _PIOD_BANK_D + _OUTPUT_DATA_CLEAR;

    gpio_data_status_addr = gpio_addr + _PIOD_BANK_D + _OUTPUT_DATA_STATUS;

    *gpio_write_protection_addr = _DISABLE_WRITE_PROTECTION;

    *gpio_enable_addr = 1 << LED_PIN;
    *gpio_output_mode_addr = 1 << LED_PIN; // Output

    // If LED
    if((*gpio_data_status_addr & (1<<LED_PIN)) > 0){
        *gpio_output_clear_addr = 1 << LED_PIN;
    }else{
        *gpio_output_set_addr = 1 << LED_PIN;
    }

    return 0;
}

EDIT :

Answer for the 3) in the comments. You have to change the mmap and the assignations like so if you want it to work with all the offsets (i.e : mmap example):

#define _PIO_OFFSET                         0xFFFFFA00 // Instead of 0xFFFFF000
#define _MAP_SIZE                           0x1000  // 4096
#define _MAP_MASK                           (_MAP_SIZE - 1)
#define _PA_OFFSET                          _PIO_OFFSET & ~_MAP_MASK

And the mmap :

gpio_addr = mmap(NULL, _MAP_SIZE + _PIO_OFFSET - _PA_OFFSET, PROT_READ | PROT_WRITE, MAP_SHARED, fd, _PA_OFFSET);

And for the assignation :

gpio_enable_addr = gpio_addr + _PIO_OFFSET - (_PA_OFFSET) + _PIO_ENABLE;


问:
IntelliJ Optimize Imports for the entire scala project
One of the very useful features of IntelliJ is that when I am done editing a file, I can do a "optimize imports". this removes all the unused imports from my code.

This is very useful, but I have to do it for every file.

Can I do "optimize imports" for the entire project?

答:
Select the source root in the project tree;

1. Hit the keyboard shortcut for "Optimize import"

MAC

```<code>Cmd-shift-A
</code>```

Windows

```<code>Ctrl-shift-A
</code>```

2. You will see

3. Hit Run

Body:
Select the source root in the project tree;

1. Hit the keyboard shortcut for "Optimize import"

MAC

Cmd-shift-A

Windows

Ctrl-shift-A

2. You will see

3. Hit Run


问:
Does Android Market Accept app using WebViewClient?
I developing a web icon application.I used the below code to launch my url

Uri uri = Uri.parse("http://www.myurl.com");
 Intent intent = new Intent(Intent.ACTION_VIEW, uri);
 startActivity(intent);

Does Android Market accept this type of application?

答:
There are absolutely no restrictions on what you use in your application.

You code the app and launch it.

You just don't have to write a malicious code that steals user-data, else ur app will be killed after sometime, if Google guys find it out.


问:
Reading blob type image from mysql database in Spring mvc with jdbcTemplate
ProductController.java

```<code>@RequestMapping(value = "/adminWelcome", method = RequestMethod.GET)
public String getAdminWelcomePage(Model model) {

    System.out.println("Product List:" + productService.getAllProducts());

    model.addAttribute("productList", productService.getAllProducts());
    return "adminHomepage";
}
</code>```

ProductService.java

```<code> public List<Map<String, Object>> getAllProducts() {
    String sql = "SELECT * FROM products LIMIT 3";

    List<Map<String, Object>> products = jdbcTemplate.queryForList(sql);
    return products;

}
</code>```

Basically, this sql return the list of 3 products which are looks like
Product List:[{id=1, name=Twitter-minimal, userId=0, image=[B@96a7858, price=1213322.0, dateManufacture=2017-02-07, dateAdded=2017-02-07 15:50:12.0, category=Clothing, description=ramedadadadad}].

This is the sample of the result which I fetched from MySql database with jdbcTemplate. I upload the image using Spring MVC4 in the database. Now I want to retrieve or read the Blobimage type so that I can display those images to my jsp pages. How can I convert this Blob image so that I can properly display to pages?

The image type was defined as MultipartFile image in the domain class.

答:
yo need resource mapping in dispatcher-servlet.xml

and

add this in your jsp page..
where static as i have defined is /WEB-INF/assets/

Body:
ProductController.java

@RequestMapping(value = "/adminWelcome", method = RequestMethod.GET)
public String getAdminWelcomePage(Model model) {

    System.out.println("Product List:" + productService.getAllProducts());

    model.addAttribute("productList", productService.getAllProducts());
    return "adminHomepage";
}

ProductService.java

 public List<Map<String, Object>> getAllProducts() {
    String sql = "SELECT * FROM products LIMIT 3";

    List<Map<String, Object>> products = jdbcTemplate.queryForList(sql);
    return products;

}

Basically, this sql return the list of 3 products which are looks like
Product List:[{id=1, name=Twitter-minimal, userId=0, image=[B@96a7858, price=1213322.0, dateManufacture=2017-02-07, dateAdded=2017-02-07 15:50:12.0, category=Clothing, description=ramedadadadad}].

This is the sample of the result which I fetched from MySql database with jdbcTemplate. I upload the image using Spring MVC4 in the database. Now I want to retrieve or read the Blobimage type so that I can display those images to my jsp pages. How can I convert this Blob image so that I can properly display to pages?

The image type was defined as MultipartFile image in the domain class.


问:
Distance to a plane
I've written a simple little helper method whoch calculates the distance from a point to a plane. However, it seems to be returning nonsensical results. The code i have for creating a plane is thus:

```<code>Plane = new Plane(vertices.First().Position, vertices.Skip(1).First().Position, vertices.Skip(2).First().Position);
</code>```

Fairly simple, I hope you'll agree. It creates an XNA plane structure using three points.

Now, immediately after this I do:

```<code>foreach (var v in vertices)
{
    float d = Math.Abs(v.ComputeDistance(Plane));
    if (d > Constants.TOLERANCE)
        throw new ArgumentException("all points in a polygon must share a common plane");
}
</code>```

Using the same set of vertices I used to construct the plane, I get that exception thrown! Mathematically this is impossible, since those three points must lie on the plane.

My ComputeDistance method is:

```<code>public static float ComputeDistance(this Vector3 point, Plane plane)
{
    float dot = Vector3.Dot(plane.Normal, point);
    float value = dot - plane.D;
    return value;
}
</code>```

AsI understand it, this is correct. So what could I be doing wrong? Or might I be encountering a bug in the implementation of XNA?

Some example data:

```<code>Points:
{X:0 Y:-0.5000001 Z:0.8660254}
{X:0.75 Y:-0.5000001 Z:-0.4330128}
{X:-0.75 Y:-0.5000001 Z:-0.4330126}

Plane created:
{Normal:{X:0 Y:0.9999999 Z:0} D:0.5} //I believe D should equal -0.5?

Distance from point 1 to plane:
1.0
</code>```

答:
Ok, I'm not totally sure I understand the math here, but I suspect (based on formulas from http://mathworld.wolfram.com/Point-PlaneDistance.html among others) that

```<code>float value = dot - plane.D;
</code>```

should actually be

```<code>float value = dot / plane.D;
</code>```

EDIT: Ok, as mentioned in comments below, this didn't work.  My best suggestion then is to go look at the link or google "distance between a point and a plane" and try implementing the formula a different way.

Title: Distance to a plane

Body:
I've written a simple little helper method whoch calculates the distance from a point to a plane. However, it seems to be returning nonsensical results. The code i have for creating a plane is thus:

Plane = new Plane(vertices.First().Position, vertices.Skip(1).First().Position, vertices.Skip(2).First().Position);

Fairly simple, I hope you'll agree. It creates an XNA plane structure using three points.

Now, immediately after this I do:

foreach (var v in vertices)
{
    float d = Math.Abs(v.ComputeDistance(Plane));
    if (d > Constants.TOLERANCE)
        throw new ArgumentException("all points in a polygon must share a common plane");
}

Using the same set of vertices I used to construct the plane, I get that exception thrown! Mathematically this is impossible, since those three points must lie on the plane.

My ComputeDistance method is:

public static float ComputeDistance(this Vector3 point, Plane plane)
{
    float dot = Vector3.Dot(plane.Normal, point);
    float value = dot - plane.D;
    return value;
}

AsI understand it, this is correct. So what could I be doing wrong? Or might I be encountering a bug in the implementation of XNA?

Some example data:

Points:
{X:0 Y:-0.5000001 Z:0.8660254}
{X:0.75 Y:-0.5000001 Z:-0.4330128}
{X:-0.75 Y:-0.5000001 Z:-0.4330126}

Plane created:
{Normal:{X:0 Y:0.9999999 Z:0} D:0.5} //I believe D should equal -0.5?

Distance from point 1 to plane:
1.0

Body:
Ok, I'm not totally sure I understand the math here, but I suspect (based on formulas from http://mathworld.wolfram.com/Point-PlaneDistance.html among others) that

float value = dot - plane.D;

should actually be

float value = dot / plane.D;

EDIT: Ok, as mentioned in comments below, this didn't work.  My best suggestion then is to go look at the link or google "distance between a point and a plane" and try implementing the formula a different way.


问:
Fast element wise multiplication of a column vector with a row vector in PLS
I'm using Matlab to perform large number of iterations with partial least squares (PLS) as the algorithm for processing data in each iteration. It runs quite slow. Using profile to monitor the time used by each line of my codes shows that the line X = X-t*p', where X is a matrix of size r by c and t and p are column vectors of size r and c, costs most of the time. I think the reason can be the extending of memory by t*p' which generates a matrix from the two vectors, a well known cause that slower the computation in Matlab. Is there a way to speed up this?

The PLS codes are:

```<code>for iter = 1:maxiter % maxiter is defaultedly set as 10,000
    % preparing data....
    ......
    % perform PLS using NIPALS algorithm
    for a = 1:A
        x = X'*y;
        w = x/norm(x);
        t = X*w;
        tt = sum(t.^2);
        p = X'*(t/tt);
        q = sum(y.*t)/tt;
        X = X-t*p';     % updata X, this line costs most of the time
        y = y-t*q;        % updata y
    end

    % output w, P, q
    .......
end
</code>```

答:
To avoid deflation of X by X = X-t*p';, there are three ways, as discussed in "Computational performance and cross-validation error precision of five PLS algorithms using designed and real data sets". I used the following algorithm:

SIMPLS

```<code>for iter = 1:maxtest
    % preparing data...
    ... ...
    for a = 1:A
        % for a vector, eigenvector of S'*S is always 1
        ri = s;
        t = X*ri;
        normt = sqrt(sum(t.^2));
        t = t/normt;
        ri = ri/normt;
        % X loadings
        pi = X'*t;
        q = y'*t;
        %u = y*q;
        v = pi;
        if a > 1
            v = v-V(:,1:a-1)*(V(:,1:a-1)'*pi);
            %u = u-T(:,1:a-1)*(T(:,1:a-1)'*u);
        end
        v = v/sqrt(sum(v.^2));
        s = s-v*(v'*s);

        V(:,a) = v;
        R(:,a) = ri;
        Q(a) = q;
    end
    % PLS coefficient...
    b = R*Q;
    ...
end
</code>```

NIPALS-y

```<code>for iter = 1:maxtest
    % preparint data...
    ... ...
    % NIPALS
    for a = 1:A
        x = X'*y;
        rx = x/norm(x);
        w = rx;
        if a > 1
            rx = rx-R(:,1:a-1)*(P(:,1:a-1)'*w);
        end
        t = X*rx;
        tt = sum(t.^2);
        P(:,a) = X'*t/tt;
        q(a) = y'*t/tt;
        y = y-t*q(a);
        % W(:, a) = w;
        R(:, a) = rx;
    end

    % PLS coefficient...
    b = R*q;
    ... ...
end
</code>```

Bidiagonalization

```<code>for iter = 1:maxtest
    v = X'*y/norm(X'*y);
    u = X*v;
    normu = sqrt(sum(u.^2));
    u = u/normu;
    R(1) = normu;
    V(:,1) = v;
    U(:,1) = u;
    for a = 2:A
        v = X'*u-normu*v;
        normv = sqrt(sum(v.^2));
        v = v/normv;
        u = X*v-normv*u;
        normu = sqrt(sum(u.^2));
        u = u/normu;
        U(:,a) = u;
        V(:,a) = v;
        R(a-1,a) = normv;
        R(a,a) = normu;
    end
    % PLS coefficients...
    b = V*(R\(U'*y));
end
</code>```

Using test data with size of 43 by 195 and 10 fold cross validation, the bidiagonalization method is the fastest, consistent with the results of the paper.

Body:
I'm using Matlab to perform large number of iterations with partial least squares (PLS) as the algorithm for processing data in each iteration. It runs quite slow. Using profile to monitor the time used by each line of my codes shows that the line X = X-t*p', where X is a matrix of size r by c and t and p are column vectors of size r and c, costs most of the time. I think the reason can be the extending of memory by t*p' which generates a matrix from the two vectors, a well known cause that slower the computation in Matlab. Is there a way to speed up this?

The PLS codes are:

for iter = 1:maxiter % maxiter is defaultedly set as 10,000
    % preparing data....
    ......
    % perform PLS using NIPALS algorithm
    for a = 1:A
        x = X'*y;
        w = x/norm(x);
        t = X*w;
        tt = sum(t.^2);
        p = X'*(t/tt);
        q = sum(y.*t)/tt;
        X = X-t*p';     % updata X, this line costs most of the time
        y = y-t*q;        % updata y
    end

    % output w, P, q
    .......
end

Body:
To avoid deflation of X by X = X-t*p';, there are three ways, as discussed in "Computational performance and cross-validation error precision of five PLS algorithms using designed and real data sets". I used the following algorithm:

SIMPLS

for iter = 1:maxtest
    % preparing data...
    ... ...
    for a = 1:A
        % for a vector, eigenvector of S'*S is always 1
        ri = s;
        t = X*ri;
        normt = sqrt(sum(t.^2));
        t = t/normt;
        ri = ri/normt;
        % X loadings
        pi = X'*t;
        q = y'*t;
        %u = y*q;
        v = pi;
        if a > 1
            v = v-V(:,1:a-1)*(V(:,1:a-1)'*pi);
            %u = u-T(:,1:a-1)*(T(:,1:a-1)'*u);
        end
        v = v/sqrt(sum(v.^2));
        s = s-v*(v'*s);

        V(:,a) = v;
        R(:,a) = ri;
        Q(a) = q;
    end
    % PLS coefficient...
    b = R*Q;
    ...
end

NIPALS-y

for iter = 1:maxtest
    % preparint data...
    ... ...
    % NIPALS
    for a = 1:A
        x = X'*y;
        rx = x/norm(x);
        w = rx;
        if a > 1
            rx = rx-R(:,1:a-1)*(P(:,1:a-1)'*w);
        end
        t = X*rx;
        tt = sum(t.^2);
        P(:,a) = X'*t/tt;
        q(a) = y'*t/tt;
        y = y-t*q(a);
        % W(:, a) = w;
        R(:, a) = rx;
    end

    % PLS coefficient...
    b = R*q;
    ... ...
end

Bidiagonalization

for iter = 1:maxtest
    v = X'*y/norm(X'*y);
    u = X*v;
    normu = sqrt(sum(u.^2));
    u = u/normu;
    R(1) = normu;
    V(:,1) = v;
    U(:,1) = u;
    for a = 2:A
        v = X'*u-normu*v;
        normv = sqrt(sum(v.^2));
        v = v/normv;
        u = X*v-normv*u;
        normu = sqrt(sum(u.^2));
        u = u/normu;
        U(:,a) = u;
        V(:,a) = v;
        R(a-1,a) = normv;
        R(a,a) = normu;
    end
    % PLS coefficients...
    b = V*(R\(U'*y));
end

Using test data with size of 43 by 195 and 10 fold cross validation, the bidiagonalization method is the fastest, consistent with the results of the paper.


问:
How can I add a contraint to the root view instead of TopLayoutGuide?
My ViewController is embedded in a UINavigationController, and it has a view that should be aligned with the top of root view. The root view has dark gray background, and occupies full screen. But this is what it looks like now:

As you can see, the root view is displayed below the status bar, which is expected. But the subview (black) is displayed below a white strip. I guess this is the top layout guide, and my subview has a constraint with its top equal to the bottom of the top layout guide. After I remove this constraint, I cannot add a constraint from my subview to the root view by Ctrl-dragging, Xcode always set up the constraint with top layout guide.

My question is:

How can I add a constraint top of subview == top of root view?

Why does the top layout guide occupy the white region?

答:
```<code>self.automaticallyAdjustsScrollViewInsets = true
</code>```

The default value of this property is true, which lets container view controllers know that they should adjust the scroll view insets of this view controller’s view to account for screen areas consumed by a status bar, search bar, navigation bar, toolbar, or tab bar. Set this property to false if your view controller implementation manages its own scroll view inset adjustments.

You can also set this property from Interface Builder

Body:
self.automaticallyAdjustsScrollViewInsets = true

The default value of this property is true, which lets container view controllers know that they should adjust the scroll view insets of this view controller’s view to account for screen areas consumed by a status bar, search bar, navigation bar, toolbar, or tab bar. Set this property to false if your view controller implementation manages its own scroll view inset adjustments.

You can also set this property from Interface Builder


问:
modify the css for font awesome
I am using this file to implement icons on my input button

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type=button class="submitter" onClick="location.href='../test.htm'" value=" Pre-payment"/></code>```

my Css file includes the following code

input[type="button"] {
    font-family: FontAwesome;
}```

The problem is I want input button value to be of the font that is consistent with my site. Right not the words "Pre-payment" on my button are taking up fonts from font awesome . If I remove font awesome and add my own font family the icon does not appear.

Any suggestions/ Ideas?

I tried to download the font awesome css file and modify it manually from whatever site it is on, but I can't find a copy of it.

答:
Take another aproach, instead of assigning the font-awesome directly to the input assign it as

```<code>input[type="button"]:before{ content: 'fontawesomeCode', font-family: FontAwesome }
</code>```

While keeping pre-payment text on the button and aligning it with padding.

Title: modify the css for font awesome

Body:
I am using this file to implement icons on my input button

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<input type=button class="submitter" onClick="location.href='../test.htm'" value=" Pre-payment"/>

my Css file includes the following code

input[type="button"] {
    font-family: FontAwesome;
}

The problem is I want input button value to be of the font that is consistent with my site. Right not the words "Pre-payment" on my button are taking up fonts from font awesome . If I remove font awesome and add my own font family the icon does not appear.

Any suggestions/ Ideas?

I tried to download the font awesome css file and modify it manually from whatever site it is on, but I can't find a copy of it.

Body:
Take another aproach, instead of assigning the font-awesome directly to the input assign it as

input[type="button"]:before{ content: 'fontawesomeCode', font-family: FontAwesome }

While keeping pre-payment text on the button and aligning it with padding.


问:
ip route get from a different routing table
Why does "ip route get" not provide a TABLE_ID SELECTOR?

I am actually using netlink to get routes from a routing table (table ID 2) and I want to get a specific route and not dump the entire routing table and filter in user land.

I was looking at "ip route" code as an example and it seems it does not have the ability to do it using "ip route get" command. The only option it seems is to dump the entire routing table.

Any ideas/pointers?

答:
You can 'mark' the packets in that command.

As in, assuming table id 2 has fwmark 2 in ip rule, ip route get IP/cidr mark 2.


问:
What's short Command for making comment and Uncomment the Code?
Short Command for making comment and vice-versa?</p>

答: Command-slash. Simple.</p>

Body: Command-slash. Simple.


问:
Optimize with Multi Column Index MYSQL
Looking for ways to optimize the following query in MySQL. I have tried creating a multi column index on sales_date, serviceID, and initalStatus but it does not get used. I've tried to research but am new to optimization and cannot seem to find an answer that fits. Below is the query:

```<code>SELECT
COUNT(id) as TotalAccounts,
AVG(sale_value) AS SaleValue,
AVG(credit_card = 1) * 100 AS CreditCard,
SUM(CASE WHEN pre_status = 1 AND bill_status = 'current' THEN 1
ELSE 0
END) AS Active,
SUM(CASE WHEN pre_status = 1 AND bill_status = 'past' THEN 1
ELSE 0
END) AS PastDue,
SUM(CASE WHEN `status` = 0 AND bill_status = 'past' THEN 1
ELSE 0
END) AS Canceled
FROM table_x
WHERE sales_date >= CAST('2015-01-01' AS DATE)
AND sales_date <= CAST('2016-01-01' AS DATE)
AND serviceID = 1
AND initialStatus = 1
</code>```

And the EXPLAIN output:

```<code>id:            '1',
select_type:   'SIMPLE',
table:         'table_x',
type:          'ALL',
possible_keys: 'sales_date,Combo sales_date office_id,salesDate_serviceID_initalStatus',
key:           NULL,
key_len:       NULL,
ref:           NULL,
rows:          '177585',
Extra:         'Using where'
</code>```

For context, total records: 204,830. Records in my date range: 65,491.

答:
You should do better with an index on columns in a different order:

```<code>ALTER TABLE table_x ADD INDEX (serviceID, initialStatus, sales_date);
</code>```

The order of columns in the index is important. Your condition on sales_date is a range condition, i.e. it may match multiple values. Whereas the other two conditions on serviceID and initialStatus are equality conditions that match one value (or zero if the value is not found).

It's generally true that in an index lookup, all the equality conditions must be on columns that are leftmost in the multi-column index. Once a column of the index is used for a range condition, any further columns to the right in the index are not used.

Suppose an index on columns (A, B, C).

A condition like WHERE A=1 AND B=2 AND C=3 will use all three columns of the index.

A condition like WHERE A=1 AND B>2 AND C=3 will use only columns A and B in the index. Then the condition for column C will be applied, row-by-row, on all the rows that matched the A and B conditions.

A condition like WHERE A>1 AND B=2 AND C=3 will only use the first column on A for the index lookup.

The order of terms in your WHERE clause does not need to be the same as the order of columns in the index definition. MySQL knows how to rearrange the terms to match the column order.

You might like my presentation How to Design Indexes, Really.

Title: Optimize with Multi Column Index MYSQL

Body:
Looking for ways to optimize the following query in MySQL. I have tried creating a multi column index on sales_date, serviceID, and initalStatus but it does not get used. I've tried to research but am new to optimization and cannot seem to find an answer that fits. Below is the query:

SELECT
COUNT(id) as TotalAccounts,
AVG(sale_value) AS SaleValue,
AVG(credit_card = 1) * 100 AS CreditCard,
SUM(CASE WHEN pre_status = 1 AND bill_status = 'current' THEN 1
ELSE 0
END) AS Active,
SUM(CASE WHEN pre_status = 1 AND bill_status = 'past' THEN 1
ELSE 0
END) AS PastDue,
SUM(CASE WHEN `status` = 0 AND bill_status = 'past' THEN 1
ELSE 0
END) AS Canceled
FROM table_x
WHERE sales_date >= CAST('2015-01-01' AS DATE)
AND sales_date <= CAST('2016-01-01' AS DATE)
AND serviceID = 1
AND initialStatus = 1

And the EXPLAIN output:

id:            '1',
select_type:   'SIMPLE',
table:         'table_x',
type:          'ALL',
possible_keys: 'sales_date,Combo sales_date office_id,salesDate_serviceID_initalStatus',
key:           NULL,
key_len:       NULL,
ref:           NULL,
rows:          '177585',
Extra:         'Using where'

For context, total records: 204,830. Records in my date range: 65,491.

Body:
You should do better with an index on columns in a different order:

ALTER TABLE table_x ADD INDEX (serviceID, initialStatus, sales_date);

The order of columns in the index is important. Your condition on sales_date is a range condition, i.e. it may match multiple values. Whereas the other two conditions on serviceID and initialStatus are equality conditions that match one value (or zero if the value is not found).

It's generally true that in an index lookup, all the equality conditions must be on columns that are leftmost in the multi-column index. Once a column of the index is used for a range condition, any further columns to the right in the index are not used.

Suppose an index on columns (A, B, C).

A condition like WHERE A=1 AND B=2 AND C=3 will use all three columns of the index.

A condition like WHERE A=1 AND B>2 AND C=3 will use only columns A and B in the index. Then the condition for column C will be applied, row-by-row, on all the rows that matched the A and B conditions.

A condition like WHERE A>1 AND B=2 AND C=3 will only use the first column on A for the index lookup.

The order of terms in your WHERE clause does not need to be the same as the order of columns in the index definition. MySQL knows how to rearrange the terms to match the column order.

You might like my presentation How to Design Indexes, Really.


问:
DOES this App use the Advertising identifier (IDFA)?
I have uploaded my iOS a few days ago. now I am getting this message

Does this app use the Advertising Identifier (IDFA)?
The Advertising Identifier (IDFA) is a unique ID for each iOS device and is the only way to offer targeted ads. Users can choose to limit ad targeting on their iOS device.

Yes

No
Ensure that you select the correct answer for Advertising Identifier (IDFA) usage. If your app does contain the IDFA and you select No, the binary will be permanently rejected and you will have to submit a different binary.

my App does not contain any ads but it shows HTML pages on click on buttons.
should I select yes or no?

答:
I have develop an app which is live on App Store. It is not showing ads but it shows HTML pages same as in your scenario. I always select it as NO.

So if you are not using IDFA, you should also select it as NO.


问:
Java application with JNI
I am new to java and want to develop a java application which will run continuously like a server.

Is it possible in Java to develop a UI less application which will work continuously? This application should also have JNI support, so functions exported using JNI should get called from a C++ application.

Can anybody tell me the pointers to start?

Help is appreciated, thanks.

Vishal N

答:
Yes, you can run Java as service (daemon). You can simply run your code a "daemonize" it. This way, it will be detached from terminal sessions and will run in background.

Take a look here:

https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo022

to see how you can run service inside C.

And here, to check out how to run service part in Java:

https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo029

Have fun with JNI!

Title: Java application with JNI


问:
How to pass a (byte[] lpData) with integer value to RegSetValueExW P/Invoke
I have this P/Invoke RegSetValueExW that sets the value to the registry key. in C#

```<code>[DllImport("coredll.dll", EntryPoint = "RegSetValueExW")]
public static extern int RegSetValueExW(uint hKey, string lpValueName,
            uint lpReserved,
            uint lpType,
            byte[] lpData,
            uint lpcbData);
</code>```

I'm having a problem with the 4th param byte[] lpdata. I need to pass a DWORD with a value of 5 (int) in it. Everything is OK if I pass a string (REG_SZ), just need to convert using the GetBytes function.

If I call GetBytes("5") it converts it to ascii value
of 53 so it writes 53 on the registry value instead of 5

答:
If you need to pass an integer value you can simply cast it to byte</p>

```<code>byte[] lpData = new byte[] { (byte)5 };
</code>```

OwnerDisplayName: Roy Astro

Body:
I have this P/Invoke RegSetValueExW that sets the value to the registry key. in C#

[DllImport("coredll.dll", EntryPoint = "RegSetValueExW")]
public static extern int RegSetValueExW(uint hKey, string lpValueName,
            uint lpReserved,
            uint lpType,
            byte[] lpData,
            uint lpcbData);

I'm having a problem with the 4th param byte[] lpdata. I need to pass a DWORD with a value of 5 (int) in it. Everything is OK if I pass a string (REG_SZ), just need to convert using the GetBytes function.

If I call GetBytes("5") it converts it to ascii value
of 53 so it writes 53 on the registry value instead of 5

Body:
If you need to pass an integer value you can simply cast it to byte

byte[] lpData = new byte[] { (byte)5 };


问:
Difference between same value in array using only one loop javascript
How to find the difference between the min and max indexes of the same value in an array with one loop with complexity exactly O(N)?

For example, given array A:

```<code>[4, 6, 2, 2, 6, 6, 1];
</code>```

the function returns 4.

答:
```<code>   var arr = [4, 6, 2, 2, 6, 6, 1];
    function test(arr) {
        var resultArr = [];
        arr.map(function (v, i, a) {
            for (var j = arr.length - 1; j >= 0; j--) {
                if (v == arr[j]) {
                    resultArr.push({value: v, result: j - i});
//                    console.log(v+'的折扣值'+(j-i));
                    break;
                }
            }
        })
        resultArr.sort(function (a, b) {
            return b.result - a.result;
        })
        console.log(resultArr[0])
    }
    test(arr);
</code>```

Body:
How to find the difference between the min and max indexes of the same value in an array with one loop with complexity exactly O(N)?

For example, given array A:

[4, 6, 2, 2, 6, 6, 1];

the function returns 4.