问:
Comparing objects
I have a class it contains some string members, some double members and some array objects.

I create two objects of this class, is there any simplest, efficient way of comparing these objects and say their equal? Any suggestions?

I know how to write a compare function, but will it be time consuming.

答:
The only way you can really do this is to override bool Object.Equals(object other) to return true when your conditions for equality are met, and return false otherwise.  You must also override int Object.GetHashCode() to return an int computed from all of the data that you consider when overriding Equals().

As an aside, note that the contract for GetHashCode() specifies that the return value must be equal for two objects when Equals() would return true when comparing them.  This means that return 0; is a valid implementation of GetHashCode() but it will cause inefficiencies when objects of your class are used as dictionary keys, or stored in a HashSet<T>.

The way I implement equality is like this:

```<code>public class Foo : IEquatable<Foo>
{
    public bool Equals(Foo other)
    {
        if (other == null)
            return false;

        if (other == this)
            return true; // Same object reference.

        // Compare this to other and return true/false as appropriate.
    }

    public override bool Equals(Object other)
    {
        return Equals(other as Foo);
    }

    public override int GetHashCode()
    {
        // Compute and return hash code.
    }
}
</code>```

A simple way of implementing GetHashCode() is to XOR together the hash codes of all of the data you consider for equality in Equals().  So if, for example, the properties you compare for equality are string FirstName; string LastName; int Id;, your implementation might look like:

```<code>public override int GetHashCode()
{
    return (FirstName != null ? FirstName.GetHashCode() : 0) ^
        (LastName != null ? LastName.GetHashCode() : 0) ^
        Id; // Primitives of <= 4 bytes are their own hash codes
}
</code>```

I typically do not override the equality operators, as most of the time I'm concerned with equality only for the purposes of dictionary keys or collections.  I would only consider overriding the equality operators if you are likely to do more comparisons by value than by reference, as it is syntactically less verbose.  However, you have to remember to change all places where you use == or != on your object (including in your implementation of Equals()!) to use Object.ReferenceEquals(), or to cast both operands to object.  This nasty gotcha (which can cause infinite recursion in your equality test if you are not careful) is one of the primary reasons I rarely override these operators.

Title: Comparing objects

Body:
The only way you can really do this is to override bool Object.Equals(object other) to return true when your conditions for equality are met, and return false otherwise.  You must also override int Object.GetHashCode() to return an int computed from all of the data that you consider when overriding Equals().

As an aside, note that the contract for GetHashCode() specifies that the return value must be equal for two objects when Equals() would return true when comparing them.  This means that return 0; is a valid implementation of GetHashCode() but it will cause inefficiencies when objects of your class are used as dictionary keys, or stored in a HashSet<T>.

The way I implement equality is like this:

public class Foo : IEquatable<Foo>
{
    public bool Equals(Foo other)
    {
        if (other == null)
            return false;

        if (other == this)
            return true; // Same object reference.

        // Compare this to other and return true/false as appropriate.
    }

    public override bool Equals(Object other)
    {
        return Equals(other as Foo);
    }

    public override int GetHashCode()
    {
        // Compute and return hash code.
    }
}

A simple way of implementing GetHashCode() is to XOR together the hash codes of all of the data you consider for equality in Equals().  So if, for example, the properties you compare for equality are string FirstName; string LastName; int Id;, your implementation might look like:

public override int GetHashCode()
{
    return (FirstName != null ? FirstName.GetHashCode() : 0) ^
        (LastName != null ? LastName.GetHashCode() : 0) ^
        Id; // Primitives of <= 4 bytes are their own hash codes
}

I typically do not override the equality operators, as most of the time I'm concerned with equality only for the purposes of dictionary keys or collections.  I would only consider overriding the equality operators if you are likely to do more comparisons by value than by reference, as it is syntactically less verbose.  However, you have to remember to change all places where you use == or != on your object (including in your implementation of Equals()!) to use Object.ReferenceEquals(), or to cast both operands to object.  This nasty gotcha (which can cause infinite recursion in your equality test if you are not careful) is one of the primary reasons I rarely override these operators.


来源: stackexchange

问:
Excel VBA: Insert N number of Sheets based on cell value
I'm new in Excel VBA. I want to insert number of cells based on a cell value.

I have sheet1, i want to use b4 as a reference as to the number of sheets (which is a template) to be inserted.

Example, if value of b4 = 4, I'd like to copy the template sheet 4 times.

How do i do that in vba?

THANKS. :)

答:
Or something like this...</p>

```<code>Sub CopyTemplate()
Dim ws As Worksheet, wsTemplate As Worksheet
Dim n As Integer, i As Long
Application.ScreenUpdating = False
Set ws = Sheets("Sheet1")
Set wsTemplate = Sheets("Template")     'Where Template is the name of Template Sheet, change it as required.
n = ws.Range("B4").Value
If n > 0 Then
    For i = 1 To n
        wsTemplate.Copy after:=Sheets(Sheets.Count)
        ActiveSheet.Name = i
    Next i
End If
Application.ScreenUpdating = True
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Or something like this...

Sub CopyTemplate()
Dim ws As Worksheet, wsTemplate As Worksheet
Dim n As Integer, i As Long
Application.ScreenUpdating = False
Set ws = Sheets("Sheet1")
Set wsTemplate = Sheets("Template")     'Where Template is the name of Template Sheet, change it as required.
n = ws.Range("B4").Value
If n > 0 Then
    For i = 1 To n
        wsTemplate.Copy after:=Sheets(Sheets.Count)
        ActiveSheet.Name = i
    Next i
End If
Application.ScreenUpdating = True
End Sub


问:
Eloquent: get only the date from timestamp
I want to get all the entries of a specific day for a user.. I don't know how to format the query.

```<code>public function getEntry()
{
    $entries = Journal::where('id', '=', Auth::id())
    ->where('created_at', '=', '\Carbon\Carbon::now()->format("l j F Y")')
    ->get()->first();
    return view('home')->with(compact('entries'));
}
</code>```

I do not know how to format that 'created_at' to match the server time. Any help will be largely appreciated. Thank You.

答:
Use whereDate() to get all entries for the specific day:

```<code>->whereDate('created_at', Carbon::today());
</code>```

Or use whereBetween():

```<code>->whereBetween('created_at', [Carbon::now()->startOfDay(), Carbon::now()->endOfDay()])
</code>```

Or simple where():

```<code>->where('created_at', '>', Carbon::now()->startOfDay())
->where('created_at', '<', Carbon::now()->endOfDay())
</code>```

Body:
I want to get all the entries of a specific day for a user.. I don't know how to format the query.

public function getEntry()
{
    $entries = Journal::where('id', '=', Auth::id())
    ->where('created_at', '=', '\Carbon\Carbon::now()->format("l j F Y")')
    ->get()->first();
    return view('home')->with(compact('entries'));
}

I do not know how to format that 'created_at' to match the server time. Any help will be largely appreciated. Thank You.

Body:
Use whereDate() to get all entries for the specific day:

->whereDate('created_at', Carbon::today());

Or use whereBetween():

->whereBetween('created_at', [Carbon::now()->startOfDay(), Carbon::now()->endOfDay()])

Or simple where():

->where('created_at', '>', Carbon::now()->startOfDay())
->where('created_at', '<', Carbon::now()->endOfDay())


问:
Append data to div using jquery
Can I know how can we append the title and message to the div using jquery for every row? The issue with my code is that each of the data is not being displayed in a row.</p>

```<code><!--
    For instance: Title1
                  Message1
                  Title2
                  Message2   -->

<div class="widget-box">
     <div class="widget-title bg_lo"  data-toggle="collapse" href="#collapseG3" > <span class="icon"> <i class="icon-chevron-down"></i> </span>
        <h5>Topic</h5>
      </div>
      <div id="announcement" class="widget-content nopadding updates collapse in" id="collapseG3">
        <div class="new-update clearfix">
          <div class="update-done"><strong id ="title"><!-- post.title --></strong></a> <span id ="message"><!-- post.message --></span> </div>
        </div>
    </div>
</div>

<script>
     $.ajax({
         url: '/test/back-api/admin/announcements',
         method: 'GET',
         success: function(d){
         if(d.result){
             var posts = d.data;
             for(var i=0; i < posts.length; i++){
             var post = posts[i];
             $('#announcement').append(post.title, post.message);
             }
         }else{
             $('#announcement').append("<div> </div>");
         }
         }
     });
</script>
</code>```

答:
Here is a snippet showing the use case

SNIPPET

var message_container = '

';

$("#add").on('click',function(){
      var message= $(message_container);
      var post = { title: "
title
", message: "
message
"};
      message.find('#title').append(post.title);
      message.find('#message').append(post.message);
      $("#announcement").append(message);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget-box">
     <div class="widget-title bg_lo"  data-toggle="collapse" href="#collapseG3" > <span class="icon"> <i class="icon-chevron-down"></i> </span>
        <h5>Topic</h5>
      </div>
      <div id="announcement" class="widget-content nopadding updates collapse in" id="collapseG3">
    </div>
</div>

<button id="add">Add</button></code>```

You can do the same thing in ajax

```<code>var message_container = '<div class="new-update clearfix"><div class="update-done"><strong id ="title"><!-- post.title --></strong></a> <span id ="message"><!-- post.message --></span> </div></div>';

$.ajax({
      url: '/test/back-api/admin/announcements',
      method: 'GET',
      success: function(d) {
        if (d.result) {
          var posts = d.data;
          for (var i = 0; i < posts.length; i++) {
            var post = posts[i];

            var message = $(message_container);

            message.find('#title').append(post.title);
            message.find('#message').append(post.message);
            $("#announcement").append(message);
          }
 });
</code>```

Title: Append data to div using jquery

Body:
Can I know how can we append the title and message to the div using jquery for every row? The issue with my code is that each of the data is not being displayed in a row.

Topic

Body:
Here is a snippet showing the use case

SNIPPET

var message_container = '<div class="new-update clearfix"><div class="update-done"><strong id ="title"><!-- post.title --></strong></a> <span id ="message"><!-- post.message --></span> </div></div>';

$("#add").on('click',function(){
      var message= $(message_container);
      var post = { title: "<h1>title</h1>", message: "<p>message</p>"};
      message.find('#title').append(post.title);
      message.find('#message').append(post.message);
      $("#announcement").append(message);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="widget-box">
     <div class="widget-title bg_lo"  data-toggle="collapse" href="#collapseG3" > <span class="icon"> <i class="icon-chevron-down"></i> </span>
        <h5>Topic</h5>
      </div>
      <div id="announcement" class="widget-content nopadding updates collapse in" id="collapseG3">
    </div>
</div>

<button id="add">Add</button>

You can do the same thing in ajax

var message_container = '<div class="new-update clearfix"><div class="update-done"><strong id ="title"><!-- post.title --></strong></a> <span id ="message"><!-- post.message --></span> </div></div>';

$.ajax({
      url: '/test/back-api/admin/announcements',
      method: 'GET',
      success: function(d) {
        if (d.result) {
          var posts = d.data;
          for (var i = 0; i < posts.length; i++) {
            var post = posts[i];

            var message = $(message_container);

            message.find('#title').append(post.title);
            message.find('#message').append(post.message);
            $("#announcement").append(message);
          }
 });


问:
Move ImageView from one layout to another layout within same activity using animation
I want to translate this imageview from relative_bottom to relative_top layout through animation. I want to put that image in center of relative_top layout. this is my splashscreen so i want this to transit automatically.

here is hiiii as imageview.I want to animate this automatically:

I want to place this image here with animation

I dont know how to set exact position.

What should I add to get such output? I have tried many ways but couldn't get a solution.

Sample xml file:

```<code><LinearLayout android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       android:background="@drawable/background"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/bg"
            android:layout_weight="2"
            android:layout_gravity="center"
            android:id="@+id/relative_top"
            android:orientation="vertical">

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:paddingLeft="50dp"
            android:paddingRight="50dp"
            android:id="@+id/bottom"
            android:layout_gravity="center_horizontal"
            android:gravity="top">
            <ProgressBar>
               ....
               </Progressbar>
            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/relative_bottom"
                android:layout_alignTop="@id/progressBar"
                android:layout_centerInParent="true"
                >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/imageview"
                    android:src="@drawable/logo"
                    android:scaleType="fitCenter"
                    />

            </RelativeLayout>

        </RelativeLayout>

</LinearLayout>
</code>```

答:
Copy from here

Add

```<code>compile 'com.android.support:transition:25.2.0'
</code>```

to your app dependencies.
Then, add this line before change gravity (TransitionManager from android.support.transition package)

```<code>TransitionManager.beginDelayedTransition(parentOfAnimatedView);
</code>```

For example:

```<code>mContainer.setOnClickListener(v -> {
        TransitionManager.beginDelayedTransition((ViewGroup) mContainer.getParent());
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mContainer.getLayoutParams();
        layoutParams.gravity = Gravity.TOP;
        mContainer.setLayoutParams(layoutParams);
    });
</code>```

Body:
I want to translate this imageview from relative_bottom to relative_top layout through animation. I want to put that image in center of relative_top layout. this is my splashscreen so i want this to transit automatically.

here is hiiii as imageview.I want to animate this automatically:

I want to place this image here with animation

I dont know how to set exact position.

What should I add to get such output? I have tried many ways but couldn't get a solution.

Sample xml file:

<LinearLayout android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       android:background="@drawable/background"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/bg"
            android:layout_weight="2"
            android:layout_gravity="center"
            android:id="@+id/relative_top"
            android:orientation="vertical">

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:paddingLeft="50dp"
            android:paddingRight="50dp"
            android:id="@+id/bottom"
            android:layout_gravity="center_horizontal"
            android:gravity="top">
            <ProgressBar>
               ....
               </Progressbar>
            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/relative_bottom"
                android:layout_alignTop="@id/progressBar"
                android:layout_centerInParent="true"
                >
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/imageview"
                    android:src="@drawable/logo"
                    android:scaleType="fitCenter"
                    />

            </RelativeLayout>

        </RelativeLayout>

</LinearLayout>

Body:
Copy from here

Add

compile 'com.android.support:transition:25.2.0'

to your app dependencies.
Then, add this line before change gravity (TransitionManager from android.support.transition package)

TransitionManager.beginDelayedTransition(parentOfAnimatedView);

For example:

mContainer.setOnClickListener(v -> {
        TransitionManager.beginDelayedTransition((ViewGroup) mContainer.getParent());
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mContainer.getLayoutParams();
        layoutParams.gravity = Gravity.TOP;
        mContainer.setLayoutParams(layoutParams);
    });


问:
show json data from foreach in view using core php
this is json data :

```<code>{"activities":[{"id":"23442","title":"coldplay","author":"ekkk@abc.com","modified":"due","action":"updated","date":"2017-05-31 12:59:27","message":"Updated the due date to 2017-07-12 10:30:00"},{"id":"23650","title":"Task For Timesheet viewer ","author":"tkkl@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-31 09:51:35","message":"Accepted task"},{"id":"23650","title":"Task For Timesheet viewer ","author":"ekkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-31 09:50:55","message":"Accepted task"},{"id":"23607","title":"project 3","author":"ekkk@abc.com","modified":"status","action":"updated","date":"2017-05-30 15:40:11","message":"Deleted task"},{"id":"23645","title":"naiman bug 2","author":"ekkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-29 11:58:38","message":"Accepted task"},{"id":"23645","title":"naiman bug 2","author":"nkkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-29 11:58:07","message":"Accepted task"}]}
</code>```

To view this data in a table, i have used foreach loop in the view file. but it is not working showing, Warning: Invalid argument supplied for foreach(). This is how i did

```<code><tbody>
            <tr>
            <?php foreach($notifications as $key => $value) {     ?>
                        <td><?php echo $value ?></td>
                    <?php } ?>
            </tr>
        </tbody>
</code>```

答:
Use it as </p>

```<code><tbody>
        <tr>
        <?php
$notifications = json_decode('{"activities":[{"id":"23442","title":"coldplay","author":"ekkk@abc.com","modified":"due","action":"updated","date":"2017-05-31 12:59:27","message":"Updated the due date to 2017-07-12 10:30:00"},{"id":"23650","title":"Task For Timesheet viewer ","author":"tkkl@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-31 09:51:35","message":"Accepted task"},{"id":"23650","title":"Task For Timesheet viewer ","author":"ekkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-31 09:50:55","message":"Accepted task"},{"id":"23607","title":"project 3","author":"ekkk@abc.com","modified":"status","action":"updated","date":"2017-05-30 15:40:11","message":"Deleted task"},{"id":"23645","title":"naiman bug 2","author":"ekkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-29 11:58:38","message":"Accepted task"},{"id":"23645","title":"naiman bug 2","author":"nkkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-29 11:58:07","message":"Accepted task"}]}');
foreach($notifications->activities as $key => $value) {     ?>
                    <td><?php  echo $value->message;//or whatever you like  ?></td>
                <?php } ?>
        </tr>
    </tbody>
</code>```

Body:
this is json data :

{"activities":[{"id":"23442","title":"coldplay","author":"ekkk@abc.com","modified":"due","action":"updated","date":"2017-05-31 12:59:27","message":"Updated the due date to 2017-07-12 10:30:00"},{"id":"23650","title":"Task For Timesheet viewer ","author":"tkkl@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-31 09:51:35","message":"Accepted task"},{"id":"23650","title":"Task For Timesheet viewer ","author":"ekkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-31 09:50:55","message":"Accepted task"},{"id":"23607","title":"project 3","author":"ekkk@abc.com","modified":"status","action":"updated","date":"2017-05-30 15:40:11","message":"Deleted task"},{"id":"23645","title":"naiman bug 2","author":"ekkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-29 11:58:38","message":"Accepted task"},{"id":"23645","title":"naiman bug 2","author":"nkkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-29 11:58:07","message":"Accepted task"}]}

To view this data in a table, i have used foreach loop in the view file. but it is not working showing, Warning: Invalid argument supplied for foreach(). This is how i did

            <?php foreach($notifications as $key => $value) {     ?>
                        <?php echo $value ?>
                    <?php } ?>

Body:
Use it as

<tbody>
        <tr>
        <?php
$notifications = json_decode('{"activities":[{"id":"23442","title":"coldplay","author":"ekkk@abc.com","modified":"due","action":"updated","date":"2017-05-31 12:59:27","message":"Updated the due date to 2017-07-12 10:30:00"},{"id":"23650","title":"Task For Timesheet viewer ","author":"tkkl@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-31 09:51:35","message":"Accepted task"},{"id":"23650","title":"Task For Timesheet viewer ","author":"ekkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-31 09:50:55","message":"Accepted task"},{"id":"23607","title":"project 3","author":"ekkk@abc.com","modified":"status","action":"updated","date":"2017-05-30 15:40:11","message":"Deleted task"},{"id":"23645","title":"naiman bug 2","author":"ekkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-29 11:58:38","message":"Accepted task"},{"id":"23645","title":"naiman bug 2","author":"nkkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-29 11:58:07","message":"Accepted task"}]}');
foreach($notifications->activities as $key => $value) {     ?>
                    <td><?php  echo $value->message;//or whatever you like  ?></td>
                <?php } ?>
        </tr>
    </tbody>


答:
You are trying to print an object, which is not a right thing to do. You should be printing scalars this object contains.</p>

```<code>$s = '{"activities":[{"id":"23442","title":"coldplay","author":"ekkk@abc.com","modified":"due","action":"updated","date":"2017-05-31 12:59:27","message":"Updated the due date to 2017-07-12 10:30:00"},{"id":"23650","title":"Task For Timesheet viewer ","author":"tkkl@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-31 09:51:35","message":"Accepted task"},{"id":"23650","title":"Task For Timesheet viewer ","author":"ekkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-31 09:50:55","message":"Accepted task"},{"id":"23607","title":"project 3","author":"ekkk@abc.com","modified":"status","action":"updated","date":"2017-05-30 15:40:11","message":"Deleted task"},{"id":"23645","title":"naiman bug 2","author":"ekkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-29 11:58:38","message":"Accepted task"},{"id":"23645","title":"naiman bug 2","author":"nkkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-29 11:58:07","message":"Accepted task"}]}';

$data = json_decode ($s);
$notifications = $data->activities;

foreach($notifications as $key => $notification) {
    echo ($notification->id);
}
</code>```

Title: show json data from foreach in view using core php

Body:
You are trying to print an object, which is not a right thing to do. You should be printing scalars this object contains.

$s = '{"activities":[{"id":"23442","title":"coldplay","author":"ekkk@abc.com","modified":"due","action":"updated","date":"2017-05-31 12:59:27","message":"Updated the due date to 2017-07-12 10:30:00"},{"id":"23650","title":"Task For Timesheet viewer ","author":"tkkl@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-31 09:51:35","message":"Accepted task"},{"id":"23650","title":"Task For Timesheet viewer ","author":"ekkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-31 09:50:55","message":"Accepted task"},{"id":"23607","title":"project 3","author":"ekkk@abc.com","modified":"status","action":"updated","date":"2017-05-30 15:40:11","message":"Deleted task"},{"id":"23645","title":"naiman bug 2","author":"ekkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-29 11:58:38","message":"Accepted task"},{"id":"23645","title":"naiman bug 2","author":"nkkk@abc.com","modified":"assigneeView","action":"updated","date":"2017-05-29 11:58:07","message":"Accepted task"}]}';

$data = json_decode ($s);
$notifications = $data->activities;

foreach($notifications as $key => $notification) {
    echo ($notification->id);
}


问:
Liferay 7 Can't add empty Web content display or Form
I can't add normally a web content display or other portlet like form etc ...

I am using LIFERAY 7 and Hypersonic as database

Here is a gif image that shows the problem

答: Try restarting the portal. Clear browser cache. Try adding the portlets to new page. This shall help.</p>


问:
Assembly x86 sub arithmetical instruction
My problem is not too big but I don't understand something and I wanted to ask for some help.

We are learning about Assembly .x86 language and I got stuck at SUB  arithmetic Instruction.

This is the code:

```<code>INCLUDE Irvine32.inc

.data

val_A    DWORD   1234h
val_B    DWORD   144h

.code

main proc

MOV     EAX, val_B   ;This works
SUB     EAX, val_A

CALL    WriteInt
CALL    Crlf

INVOKE  ExitProcess, 0
main endp

.stack
dw      100 dup(? )

end main
</code>```

When I try to put like this:

```<code>MOV    EAX, val_A
MOV    EBX, val_B
SUB    EBX, EAX
</code>```

It doesnt work. We learned that [SUB] arithmetical intstruction works just as [MOV] and [ADD] but when I try to use it as [SUB reg/reg] absolutely gives nothing only shows what is in the EAX register.
I use Visual Studio I am not sure if that's the issue.

答:
Sub instruction does work like MOV and ADD.
It does work as SUB reg/reg.
When you tried to use SUB as:

```<code>MOV EAX, val_A
MOV EBX, val_B
SUB EBX, EAX
</code>```

You didn't change EAX, and like you said, the register EAX hasn't changed.
That because the result saved in EBX.
To get the result of (1234h - 123h) into the register EAX you should code:

```<code>MOV EAX, val_A
MOV EBX, val_B
SUB EAX, EBX
</code>```

Just to be clear again, SUB instruction does work like MOV and that why the result moves into the first register. For example:

```<code>MOV EAX, 1234h
</code>```

put the number 1234h in the register EAX and not the opposite.

Body:
My problem is not too big but I don't understand something and I wanted to ask for some help.

We are learning about Assembly .x86 language and I got stuck at SUB  arithmetic Instruction.

This is the code:

INCLUDE Irvine32.inc

.data

val_A    DWORD   1234h
val_B    DWORD   144h

.code

main proc

MOV     EAX, val_B   ;This works
SUB     EAX, val_A

CALL    WriteInt
CALL    Crlf

INVOKE  ExitProcess, 0
main endp

.stack
dw      100 dup(? )

end main

When I try to put like this:

MOV    EAX, val_A
MOV    EBX, val_B
SUB    EBX, EAX

It doesnt work. We learned that [SUB] arithmetical intstruction works just as [MOV] and [ADD] but when I try to use it as [SUB reg/reg] absolutely gives nothing only shows what is in the EAX register.
I use Visual Studio I am not sure if that's the issue.

Body:
Sub instruction does work like MOV and ADD.
It does work as SUB reg/reg.
When you tried to use SUB as:

MOV EAX, val_A
MOV EBX, val_B
SUB EBX, EAX

You didn't change EAX, and like you said, the register EAX hasn't changed.
That because the result saved in EBX.
To get the result of (1234h - 123h) into the register EAX you should code:

MOV EAX, val_A
MOV EBX, val_B
SUB EAX, EBX

Just to be clear again, SUB instruction does work like MOV and that why the result moves into the first register. For example:

MOV EAX, 1234h

put the number 1234h in the register EAX and not the opposite.


问:
operator % is not working for null values
Assume the customer table is as follows.

```<code>cust_id  |  name  |   address | language
A        |   AAA  |      ZZZZ |      en
B        |   BBB  |      YYYY |
C        |   CCC  |      XXXX |      pl
D        |   DDD  |      WWWW |      en
</code>```

I want to get a plsql code that will accept user input for the language filed, and when user input;

```<code>1. 'en'; cust_id: A,B should be the result
2. 'pl'; cust_id: C should be the result
3. doesnt input a value;  cust_id: A,B,C,D should be the result

select cust_id from customer c where c.language like NVL('&lang','%');
</code>```

option 1 & 2 works fine with the above query, but 3 doesnt result any value. I think it is because % operator is not working with null values. can anyone help me to revise the query which is capable of giving results for all the 3 options?

答:
You can use the below query:

```<code>select cust_id from customer c where c.language = NVL('&lang', c.language);
</code>```

When &lang is null query will return all the rows from customer table.

Body:
Assume the customer table is as follows.

cust_id  |  name  |   address | language
A        |   AAA  |      ZZZZ |      en
B        |   BBB  |      YYYY |
C        |   CCC  |      XXXX |      pl
D        |   DDD  |      WWWW |      en

I want to get a plsql code that will accept user input for the language filed, and when user input;

1. 'en'; cust_id: A,B should be the result
2. 'pl'; cust_id: C should be the result
3. doesnt input a value;  cust_id: A,B,C,D should be the result

select cust_id from customer c where c.language like NVL('&lang','%');

option 1 & 2 works fine with the above query, but 3 doesnt result any value. I think it is because % operator is not working with null values. can anyone help me to revise the query which is capable of giving results for all the 3 options?

Body:
You can use the below query:

select cust_id from customer c where c.language = NVL('&lang', c.language);

When &lang is null query will return all the rows from customer table.


问:
Cassandra PHP driver 502 badgateway from prepared statement
I'm using this driver for cassandra: https://github.com/datastax/php-driver

Here's the code I used to create the table:

```<code>CREATE TABLE test.packages (
     packageuuid timeuuid,
     ruserid text,
     suserid text,
     timestamp int,
     PRIMARY KEY (ruserid, suserid, packageuuid, timestamp)
);
</code>```

and then I create a materialized view:

```<code>CREATE MATERIALIZED VIEW test.packages_by_userid
    AS SELECT * FROM test.packages
    WHERE ruserid IS NOT NULL
       AND suserid IS NOT NULL
       AND TIMESTAMP IS NOT NULL
       AND packageuuid IS NOT NULL
    PRIMARY KEY (ruserid, suserid, timestamp, packageuuid)
    WITH CLUSTERING ORDER BY (packageuuid DESC);
</code>```

and here's a snippet of my PHP code which causes 502 bad gateway:

```<code>$session   = $cluster->connect($keyspace);
$selectstmt = $session->prepare("SELECT suserid, susername, snickname, msg, savatar, timestamp FROM packages_by_userid WHERE ruserid IN (?, ?) AND suserid IN (?, ?) AND timestamp < ? LIMIT 40;");
$params = array('ruserid' => array($rid, $sid), 'suserid' => array($rid, $sid), 'timestamp' => $endtimestamp);
$options = array('arguments' => $params);
$future    = $session->executeAsync($selectstmt, $options);
$result    = $future->get();
</code>```

I believe I messed up with binding the parameters to the prepared statement. What's the proper way to do that in my case as I have to bind more than one value to ruserid and suserid?

Thanks to anyone who can help.

答:
I suggest you to change your data model like below :

```<code>CREATE TABLE packages (
    cnvid text,
    packageuuid timeuuid,
    ruserid text,
    suserid text,
    PRIMARY KEY (cnvid, packageuuid)
);
</code>```

Here cnvid is the conversation id. You can make the conversation id using the below function :

```<code> function makeConversationId($ruserid, $suserid ) {
    return $ruserid <= $suserid ? $ruserid . ':' . $suserid : $suserid . ':' . $ruserid ;
 }
</code>```

Whoever the sender or receiver your conversation id will be same. i.e

```<code> echo makeConversationId('1', '2') . '<br/>';
 echo makeConversationId('2', '1');
</code>```

Output :

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

Now you have the cnvid, whenever you insert/update/delete/select use the above method to make cnvid.

And though packageuuid is the timeuuid, all your packageuuid will be sorted by time.

So to query first create the cnvid (i.e 1:2) then create a timeuuid with the timestamp for which you want to query (i.e 896f8110-49d4-11e7-ade6-493d3332b999)

Check this : https://datastax.github.io/php-driver/api/Cassandra/class.Timeuuid/

So you can query to get packages of user between 1 and 2 whose timestamp greater than the given timestamp :

Example Data :

```<code> cnvid | packageuuid                          | ruserid | suserid
-------+--------------------------------------+---------+---------
   3:4 | bc0809e0-49d3-11e7-ade6-493d3332b999 |       3 |       4
   1:2 | 1f4aae70-49d1-11e7-ade6-493d3332b999 |       1 |       2
   1:2 | 237ff3b0-49d1-11e7-ade6-493d3332b999 |       2 |       1
</code>```

Query :

```<code>SELECT * FROM packages WHERE cnvid = '1:2' AND packageuuid < 896f8110-49d4-11e7-ade6-493d3332b999;
</code>```

Output :

```<code> cnvid | packageuuid                          | ruserid | suserid
-------+--------------------------------------+---------+---------
   1:2 | 1f4aae70-49d1-11e7-ade6-493d3332b999 |       1 |       2
   1:2 | 237ff3b0-49d1-11e7-ade6-493d3332b999 |       2 |       1
</code>```

So you don't need the Materialized View and In query.

Body:
I'm using this driver for cassandra: https://github.com/datastax/php-driver

Here's the code I used to create the table:

CREATE TABLE test.packages (
     packageuuid timeuuid,
     ruserid text,
     suserid text,
     timestamp int,
     PRIMARY KEY (ruserid, suserid, packageuuid, timestamp)
);

and then I create a materialized view:

CREATE MATERIALIZED VIEW test.packages_by_userid
    AS SELECT * FROM test.packages
    WHERE ruserid IS NOT NULL
       AND suserid IS NOT NULL
       AND TIMESTAMP IS NOT NULL
       AND packageuuid IS NOT NULL
    PRIMARY KEY (ruserid, suserid, timestamp, packageuuid)
    WITH CLUSTERING ORDER BY (packageuuid DESC);

and here's a snippet of my PHP code which causes 502 bad gateway:

$session   = $cluster->connect($keyspace);
$selectstmt = $session->prepare("SELECT suserid, susername, snickname, msg, savatar, timestamp FROM packages_by_userid WHERE ruserid IN (?, ?) AND suserid IN (?, ?) AND timestamp < ? LIMIT 40;");
$params = array('ruserid' => array($rid, $sid), 'suserid' => array($rid, $sid), 'timestamp' => $endtimestamp);
$options = array('arguments' => $params);
$future    = $session->executeAsync($selectstmt, $options);
$result    = $future->get();

I believe I messed up with binding the parameters to the prepared statement. What's the proper way to do that in my case as I have to bind more than one value to ruserid and suserid?

Thanks to anyone who can help.

Body:
I suggest you to change your data model like below :

CREATE TABLE packages (
    cnvid text,
    packageuuid timeuuid,
    ruserid text,
    suserid text,
    PRIMARY KEY (cnvid, packageuuid)
);

Here cnvid is the conversation id. You can make the conversation id using the below function :

 function makeConversationId($ruserid, $suserid ) {
    return $ruserid <= $suserid ? $ruserid . ':' . $suserid : $suserid . ':' . $ruserid ;
 }

Whoever the sender or receiver your conversation id will be same. i.e

 echo makeConversationId('1', '2') . '<br/>';
 echo makeConversationId('2', '1');

Output :

1:2
1:2

Now you have the cnvid, whenever you insert/update/delete/select use the above method to make cnvid.

And though packageuuid is the timeuuid, all your packageuuid will be sorted by time.

So to query first create the cnvid (i.e 1:2) then create a timeuuid with the timestamp for which you want to query (i.e 896f8110-49d4-11e7-ade6-493d3332b999)

Check this : https://datastax.github.io/php-driver/api/Cassandra/class.Timeuuid/

So you can query to get packages of user between 1 and 2 whose timestamp greater than the given timestamp :

Example Data :

 cnvid | packageuuid                          | ruserid | suserid
-------+--------------------------------------+---------+---------
   3:4 | bc0809e0-49d3-11e7-ade6-493d3332b999 |       3 |       4
   1:2 | 1f4aae70-49d1-11e7-ade6-493d3332b999 |       1 |       2
   1:2 | 237ff3b0-49d1-11e7-ade6-493d3332b999 |       2 |       1

Query :

SELECT * FROM packages WHERE cnvid = '1:2' AND packageuuid < 896f8110-49d4-11e7-ade6-493d3332b999;

Output :

 cnvid | packageuuid                          | ruserid | suserid
-------+--------------------------------------+---------+---------
   1:2 | 1f4aae70-49d1-11e7-ade6-493d3332b999 |       1 |       2
   1:2 | 237ff3b0-49d1-11e7-ade6-493d3332b999 |       2 |       1

So you don't need the Materialized View and In query.


问:
Datatable service Yajra show blank
i want to add button in Yajra, so i read http://dt54.yajrabox.com/buttons/eloquent.
Im following the step. But still show blank.

nb. if im not using datatable service running well.

Datatables class

namespace App\DataTables;

```<code>use App\employee;
use Yajra\Datatables\Services\DataTable;
class EmployeeDataTable extends DataTable
{

public function ajax()
{
return $this->datatables
->eloquent($this->query())
->make(true);
}

public function query()
{
    $query = employee::select();

    return $this->applyScopes($query);
}

public function html()
{
   return $this->builder()
                ->columns($this->getColumns())
                ->ajax('{{ url("Employee/index3") }}')
                ->parameters([
                    'dom'          => 'Bfrtip',
                    'buttons'      => ['export', 'print', 'reset', 'reload'],

                ]);
}

protected function filename()
{
    return 'employeedatatables_' . time();
}
</code>```

in Controller

```<code>use Yajra\Datatables\Facades\Datatables;
use App\DataTables\EmployeeDataTable;

public function index3(EmployeeDataTable $dataTable)
{
    return $dataTable->render('employee.users');
}
</code>```

in View

```<code>@extends('layouts.app')

@section('content')
<div class="col-md-8 col-md-offset-2">
<h3>test</h3>

{!! $dataTable->table() !!}
</div>
{!! $dataTable->scripts() !!}
@endsection
</code>```

If i used firebug, i've got error 304 not modified.
Can you tell me what my mistake,pls ?

答:
Solved.. maybe can help somebody..
this is Column search,and add action using Datatabale service

in Datatables class

```<code>public function ajax()
{

    return $this->datatables

        ->eloquent($this->query())
        ->addColumn('action', function ($query) {
                        return '<a href="#edit-'.$query->ID.'" class="btn btn-xs btn-primary"><i class="glyphicon glyphicon-edit"></i> Edit</a>
                    <a href="#delete-'.$query->ID.'" class="btn btn-xs btn-danger"><i class="glyphicon glyphicon-minus-sign"></i> Del</a>';
                    })
         ->make(true);
}

public function query()
{
    $query = employee::select('ID','cNip','vName','vBankbranch');

    return $this->applyScopes($query);
}

public function html()
{
   return $this->builder()
                ->columns($this->getColumns())
                ->addAction(['width' => '10%'])
                ->ajax('')
                 ->parameters([
                    'dom'          => 'Bfrtip',
                    'buttons'      => ['export', 'print', 'reset', 'reload'],
                    'initComplete' => "function () {
                        this.api().columns().every(function () {
                            var column = this;
                            var input = document.createElement(\"input\");
                            $(input).appendTo($(column.footer()).empty())
                            .on('change', function () {
                                column.search($(this).val(), false, false, true).draw();
                            });
                        });
                    }",
                ]);
}
</code>```

in View

```<code>@extends('layouts.app')
@section('content')
<div class="col-md-8 col-md-offset-2">
<h3>test</h3>
{!! $dataTable->table([], true) !!}
</div>
@endsection
@section('scripts')
{!! $dataTable->scripts() !!}
@endsection
</code>```

Title: Datatable service Yajra show blank

Body:
i want to add button in Yajra, so i read http://dt54.yajrabox.com/buttons/eloquent.
Im following the step. But still show blank.

nb. if im not using datatable service running well.

Datatables class

namespace App\DataTables;

use App\employee;
use Yajra\Datatables\Services\DataTable;
class EmployeeDataTable extends DataTable
{

public function ajax()
{
return $this->datatables
->eloquent($this->query())
->make(true);
}

public function query()
{
    $query = employee::select();

    return $this->applyScopes($query);
}

public function html()
{
   return $this->builder()
                ->columns($this->getColumns())
                ->ajax('{{ url("Employee/index3") }}')
                ->parameters([
                    'dom'          => 'Bfrtip',
                    'buttons'      => ['export', 'print', 'reset', 'reload'],

                ]);
}

protected function filename()
{
    return 'employeedatatables_' . time();
}

in Controller

use Yajra\Datatables\Facades\Datatables;
use App\DataTables\EmployeeDataTable;

public function index3(EmployeeDataTable $dataTable)
{
    return $dataTable->render('employee.users');
}

in View

@extends('layouts.app')

@section('content')

test

{!! $dataTable->table() !!}

{!! $dataTable->scripts() !!}
@endsection

If i used firebug, i've got error 304 not modified.
Can you tell me what my mistake,pls ?

Body:
Solved.. maybe can help somebody..
this is Column search,and add action using Datatabale service

in Datatables class

public function ajax()
{

    return $this->datatables

        ->eloquent($this->query())
        ->addColumn('action', function ($query) {
                        return '<a href="#edit-'.$query->ID.'" class="btn btn-xs btn-primary"><i class="glyphicon glyphicon-edit"></i> Edit</a>
                    <a href="#delete-'.$query->ID.'" class="btn btn-xs btn-danger"><i class="glyphicon glyphicon-minus-sign"></i> Del</a>';
                    })
         ->make(true);
}

public function query()
{
    $query = employee::select('ID','cNip','vName','vBankbranch');

    return $this->applyScopes($query);
}

public function html()
{
   return $this->builder()
                ->columns($this->getColumns())
                ->addAction(['width' => '10%'])
                ->ajax('')
                 ->parameters([
                    'dom'          => 'Bfrtip',
                    'buttons'      => ['export', 'print', 'reset', 'reload'],
                    'initComplete' => "function () {
                        this.api().columns().every(function () {
                            var column = this;
                            var input = document.createElement(\"input\");
                            $(input).appendTo($(column.footer()).empty())
                            .on('change', function () {
                                column.search($(this).val(), false, false, true).draw();
                            });
                        });
                    }",
                ]);
}

in View

@extends('layouts.app')
@section('content')
<div class="col-md-8 col-md-offset-2">
<h3>test</h3>
{!! $dataTable->table([], true) !!}
</div>
@endsection
@section('scripts')
{!! $dataTable->scripts() !!}
@endsection


问:
Bulk Remove Database Objects From Database Project
I'm currently maintaining a SQL Server database that is over 17 years old, and has a large number of unused and outdated artifacts within it.

Over the last several months we have been profiling the database to determine which of the 1800+ stored procedures are actually being used, and which ones we can safely remove.  And as of right now, we have a list of about 1300 that we are planning on removing.

This database is also checked in under our source control in a SQL Server Database Project.

Now, what I'd like to do is generate a script to remove the 1300 procedures and apply that script to the database project first, before applying the script to our Development environment.  But I can't seem to figure out a way to update the project via a script.

I've tried doing an Import > Script and importing a .sql file with DROP PROCEDURE commands, but it throws the following error whilst not removing the procedure from the project:

In the script that you provided to the import operation, one or more statements were not fully understood. These statements were moved to the ScriptsIgnoredOnImport.sql file. Review the file contents for additional information.

The contents of the file tested was the following:

```<code>Drop Procedure spProcedureName;
</code>```

I could go through the project and remove each procedure one-by-one... but there are over 1300 to remove...

Is there any way to do a bulk update (via a script or otherwise) to a database project to remove multiple database objects?

Additional Information:

Creating a shell database from the project and making updates to that will prove to be just as much effort as manually removing the 1,300 stored procedures one-by-one.  This is due to the fact that many of the stored procedures we're planning on removing contain outdated/invalid references to tables, views, functions, OPENROWSET connections, and other procedures.  Because of that, the deploy script fails, and a shell database cannot be created without modifying the individual invalid objects in the script.

Getting a backup/restore of the current database is also not a viable solution, as the current database is a little over 3 TB in size.

Because of the above limitations, I am only looking for a solution that can be applied to the database project directly without any dependency on a secondary physical database.

答:
Deploy your project to a new DB (DB_Temp)

Drop old stored procedures via TSQL

Create a new DB project and import the database schema from DB_Temp.

Update/check project settings, including Publish settings to drop SPs that are not in the project.

Deploy the project to DEV and Test environment, and test.

Drop the old project

Drop DB_Temp

UPDATE:

Alternative way:

Deploy your project to a new DB (DB_Temp)

Drop old stored procedures via TSQL

In VS, run Tools-->SQL Server-->Schema Comparison (Source: DB_Temp, Target: your project)

Press "Update" to remove the old SPs from the project

Deploy the project to DEV and Test environment, and test.

Drop DB_Temp

Body:
I'm currently maintaining a SQL Server database that is over 17 years old, and has a large number of unused and outdated artifacts within it.

Over the last several months we have been profiling the database to determine which of the 1800+ stored procedures are actually being used, and which ones we can safely remove.  And as of right now, we have a list of about 1300 that we are planning on removing.

This database is also checked in under our source control in a SQL Server Database Project.

Now, what I'd like to do is generate a script to remove the 1300 procedures and apply that script to the database project first, before applying the script to our Development environment.  But I can't seem to figure out a way to update the project via a script.

I've tried doing an Import > Script and importing a .sql file with DROP PROCEDURE commands, but it throws the following error whilst not removing the procedure from the project:

In the script that you provided to the import operation, one or more statements were not fully understood. These statements were moved to the ScriptsIgnoredOnImport.sql file. Review the file contents for additional information.

The contents of the file tested was the following:

Drop Procedure spProcedureName;

I could go through the project and remove each procedure one-by-one... but there are over 1300 to remove...

Is there any way to do a bulk update (via a script or otherwise) to a database project to remove multiple database objects?

Additional Information:

Creating a shell database from the project and making updates to that will prove to be just as much effort as manually removing the 1,300 stored procedures one-by-one.  This is due to the fact that many of the stored procedures we're planning on removing contain outdated/invalid references to tables, views, functions, OPENROWSET connections, and other procedures.  Because of that, the deploy script fails, and a shell database cannot be created without modifying the individual invalid objects in the script.

Getting a backup/restore of the current database is also not a viable solution, as the current database is a little over 3 TB in size.

Because of the above limitations, I am only looking for a solution that can be applied to the database project directly without any dependency on a secondary physical database.


问:
I am unable to trigger cordova inAppBrowser to open URLs
In my app I have a directive inside a repeater, and the directive displays the URLs to the users.

The code I have is the following:

```<code>var onDeviceReady;

onDeviceReady = function() {
  console.log("this was called");
  return window.open = cordova.InAppBrowser.open;
};
</code>```

document.addEventListener('deviceready', onDeviceReady, false);

and in the html

```<code><a href="#" on-click="window.open('{{data.url}}', '_blank', 'location=yes');">{{data.url}}</a>
</code>```

When i try to open the app on the android device, the console message is printed properly (meaning that the function should be called) but all the url is not opening at all.

My index file looks like this (in case is useful):

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <meta http-equiv="Content-Security-Policy"
          content="default-src * gap://ready file: data:; style-src 'self' 'unsafe-inline' *; font-src 'self' data: https://fonts.gstatic.com; script-src 'self' 'unsafe-inline' 'unsafe-eval' *">
    <title></title>
    <link href="css/bower.css" rel="stylesheet" id="bower-css">
    <link href="css/style.css" rel="stylesheet" id="style-css">
</head>

<body ng-app="myApp" ng-strict-di>
   <ion-nav-view class="slide-left-right" animation="slide-left-right"></ion-nav-view>

<script src="js/bower.js"></script>
<script src="cordova.js"></script>
<script src="js/app.js"></script>
<script src="js/templates.js"></script>
</body>
</html>
</code>```

And the plugins i currently have installed are the following:

cordova-plugin-inappbrowser 1.7.1 "InAppBrowser"

cordova-plugin-whitelist 1.3.2 "Whitelist"

答:
I finally managed to get it working at the end.

Basically, I replaced

ng-click="window.open('{{data.url}}', '_blank', 'location=yes');">

with a function:

```<code>ng-click="openRUL({{data.url}})">
</code>```

and then the function looks like this:

```<code>$scope.openURL = function (url){
  window.open(url, '_blank', 'location=yes')
}
</code>```

and it's working perfectly fine now.

Body:
In my app I have a directive inside a repeater, and the directive displays the URLs to the users.

The code I have is the following:

var onDeviceReady;

onDeviceReady = function() {
  console.log("this was called");
  return window.open = cordova.InAppBrowser.open;
};

document.addEventListener('deviceready', onDeviceReady, false);

and in the html

{{data.url}}

When i try to open the app on the android device, the console message is printed properly (meaning that the function should be called) but all the url is not opening at all.

My index file looks like this (in case is useful):

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <meta http-equiv="Content-Security-Policy"
          content="default-src * gap://ready file: data:; style-src 'self' 'unsafe-inline' *; font-src 'self' data: https://fonts.gstatic.com; script-src 'self' 'unsafe-inline' 'unsafe-eval' *">
    <title></title>
    <link href="css/bower.css" rel="stylesheet" id="bower-css">
    <link href="css/style.css" rel="stylesheet" id="style-css">

   <ion-nav-view class="slide-left-right" animation="slide-left-right"></ion-nav-view>

And the plugins i currently have installed are the following:

cordova-plugin-inappbrowser 1.7.1 "InAppBrowser"

cordova-plugin-whitelist 1.3.2 "Whitelist"

Body:
I finally managed to get it working at the end.

Basically, I replaced

ng-click="window.open('{{data.url}}', '_blank', 'location=yes');">

with a function:

ng-click="openRUL({{data.url}})">

and then the function looks like this:

$scope.openURL = function (url){
  window.open(url, '_blank', 'location=yes')
}

and it's working perfectly fine now.


问:
Android status bar hide/change color in splash screen
I implemented a layout-less splash screen in my app following this tutorial: https://www.bignerdranch.com/blog/splash-screens-the-right-way/

I managed to change the color of the status bar for my MainActivity and even to make it fullscreen using a theme. However none of the methods I've tried are working with the splash screen. Maybe it's because it doesn't use a layout but directly a drawable as background:

```<code><style
    name="AppTheme"
    parent="@android:style/Theme.Material.Light.NoActionBar">

    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:textColor">@color/textColor</item>
    <item name="iconColor">@color/iconColor</item>
    <item name="android:statusBarColor">@color/colorPrimaryDark</item>
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>

<style
    name="SplashTheme"
    parent="AppTheme">

    <item name="android:windowBackground">@drawable/splash_screen</item>
</style>
</code>```

I tried using a Fullscreen theme, setting android:statusBarColor in the theme used by the activity, I also tried the two following bits of code:

```<code>View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);

Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));
</code>```

These 4 methods are working for my normal activity but not for the splash screen. Is there anything I can do?

EDIT: I'm targetting minSdkVersion 23

答:
Okay, after more experiments, it turns out I had some sort of a cache problem. I tried installing my app on another phone and it worked as intended, whereas on the first phone I installed the app, it's not updating. So just so you know, the simple solution of android:statusBarColor is enough to make it work.

Now about that cache problem, it's not the first time I have it with that screen, it must be the particular condition of having no layout and a drawable as a background. I tried invalidating the cache in Android Studio, I cleaned and rebuilt the project, I uninstalled the app on the phone but nothing works. So if you are in this cofiguration, just try to run your app on another phone if you can, just to check that your solution isn't already working, just not updating on your device.

Body:
I implemented a layout-less splash screen in my app following this tutorial: https://www.bignerdranch.com/blog/splash-screens-the-right-way/

I managed to change the color of the status bar for my MainActivity and even to make it fullscreen using a theme. However none of the methods I've tried are working with the splash screen. Maybe it's because it doesn't use a layout but directly a drawable as background:

I tried using a Fullscreen theme, setting android:statusBarColor in the theme used by the activity, I also tried the two following bits of code:

View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);

Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));

These 4 methods are working for my normal activity but not for the splash screen. Is there anything I can do?

EDIT: I'm targetting minSdkVersion 23


问:
Why is javascript not part of the project architecture?
I recently came across a question where someone asked what architecture we use in the company and someone else replied LAMP.

I am not sure why we do not include javascript as a part of the architecture. Is it implied? Or is there something I am missing? What if someone is using say ECMA script or VB script instead of javascript?

答: Because "LAMP" only addresses the technologies that run on the server-side, not what runs on the client-side, like the browser, or JavaScript within the browser. (And at the time "LAMP" was coined, JavaScript saw much less usage than it does today.)</p>

ContentLicense: CC BY-SA 2.5


问:
Is virtual memory used when using Port-mapped I/O?
If I have a Memory-mapped I/O device, and I want to write to a register for this device located at address 0x16D34, the 0x16D34 address is actually a virtual address, and the CPU will translate it to a physical address first, and then write the data to the physical address.

But what about Port-mapped I/O devices (for example: a serial port), so if I want to write to a register for a serial port located at address 0x3F8, is the 0x3F8 address a physical address or a virtual address?

Edit: I am on x86 architecture.

答:
It seems your question would be the differences between memory-mapped I/O and Port-mapped IO. There normally two methods for processor to connect external devices, which are memory-mapped or port mapped I/O.

Memory-mapped I/O

Memory-mapped I/O uses the same address space to address both memory and I/O devices. So when an address is accessed by the CPU, it may refer to a portion of physical RAM, but it can also refer to memory of the I/O device (Based on Memory-mapped I/O on Wiki).

The value 0x16D34 in your first example would be virtual memory, and would be mapped to the physical memory. The I/O device would refer the same physical memory as well to allow the access from CPU.

Port mapped I/O

Port mapped I/O uses a separate, dedicated address space and is accessed via a dedicated set of microprocessor instructions. For 0x3F8 in your second example, it's the address of the own address specific to Memory and I/O devices. It's not the address shared between memory and I/O devices as we previously mentioned in Memory-mapped I/O. You might get more detailed in Memory-mapped IO vs Port-mapped IO


问:
UFT Scheduling a test by adding time dependency
I am working on scheduling an automation test every day. I have my test in the test lab and set a time dependency to the flow at 10.00 AM. I see that it is not working. Please answer the questions:

Could you please give me a possible solution to schedule the job?

Does HP ALM support scheduling?

If this doesn't work, do i have to create a batch file to execute
the test in UFT and can you please give the code for creating a
batch file to run the test with UFT?

I appreciate your help.

答:
Try this link. This should get you going:
http://www.qtptutorial.net/qtpuft-running-your-scripts-at-scheduled-time-with-ease/</p>


问:
Open a chrome extension through Selenium WebDriver using Python
I have created a chrome extension that makes API calls to database and fetches some data relevant to a website that is currently open. For example, if I open target.com and click on extension that it will give you data relevant to target.com.

I am trying to write automated tests for it through selenium web driver which I can run on a regular basis for regression testing. To test the extension, I need to first open the extension (generally we do it by clicking on the extension icon).

I have tried different ways of attempting to click on the extension icon but have not been successful. (For example, using the keyboard shortcut ALT - LEFT_ARROW - SPACE but that does not work through webdriver).

I have also tried this (mentioned here):

```<code>options = webdriver.ChromeOptions()
options.add_argument("--app-id = mbopgmdnpcbohhpnfglgohlbhfongabi")
</code>```

But above code does not help in opening extension.

I would appreciate any thoughts on how can I do this using python in Selenium Webdriver.

答:
```<code>from selenium import webdriver
option = webdriver.ChromeOptions()
option.add_extension("./testCRX/angular_ext.crx")
driver = webdriver.Chrome(chrome_options=option)
driver.get('chrome://extensions/')
</code>```

for open the added Extension: I think we can set shortkey in chrome://extensions/ -> Keyboard shortcuts ,  add the  Keyboard shortcuts to your added extension, then send  Keyboard to launch the extension.

Body:
I have created a chrome extension that makes API calls to database and fetches some data relevant to a website that is currently open. For example, if I open target.com and click on extension that it will give you data relevant to target.com.

I am trying to write automated tests for it through selenium web driver which I can run on a regular basis for regression testing. To test the extension, I need to first open the extension (generally we do it by clicking on the extension icon).

I have tried different ways of attempting to click on the extension icon but have not been successful. (For example, using the keyboard shortcut ALT - LEFT_ARROW - SPACE but that does not work through webdriver).

I have also tried this (mentioned here):

options = webdriver.ChromeOptions()
options.add_argument("--app-id = mbopgmdnpcbohhpnfglgohlbhfongabi")

But above code does not help in opening extension.

I would appreciate any thoughts on how can I do this using python in Selenium Webdriver.

Body:
from selenium import webdriver
option = webdriver.ChromeOptions()
option.add_extension("./testCRX/angular_ext.crx")
driver = webdriver.Chrome(chrome_options=option)
driver.get('chrome://extensions/')

for open the added Extension: I think we can set shortkey in chrome://extensions/ -> Keyboard shortcuts ,  add the  Keyboard shortcuts to your added extension, then send  Keyboard to launch the extension.


答:
JavaScript is a client-side technology, while Linux, Apache, MySQL and Perl/Python/PHP all have to do with the server.

There are server-side JavaScript implementations like Aptana Jaxer and node.js, but JavaScript is most commonly-used for browser behavior, and thus doesn't have much to do with the server other than through Ajax requests.

Title: Why is javascript not part of the project architecture?

Body:
I recently came across a question where someone asked what architecture we use in the company and someone else replied LAMP.

I am not sure why we do not include javascript as a part of the architecture. Is it implied? Or is there something I am missing? What if someone is using say ECMA script or VB script instead of javascript?


答:
Looks to me like your markup isn't going to work very well if you're working with a collection of records. What you're likely to end up with the way you're going is something like...

```<code><!-- Title1
     Title2
     Message1
     Message2 -->
</code>```

Change your code up a little so that you can add to the markup for each record:

```<code> $.ajax({
     url: '/test/back-api/admin/announcements',
     method: 'GET',
     success: function(d){
     if(d.result){
         var posts = d.data;
         for(var i=0; i < posts.length; i++){
         var post = posts[i];

         var Title = "<div class=\"title\">" + post.title + "</div>";
         var Message = "<div class=\"message\">" + post.message + "</div>";
         $('#announcement').append(Title, Message);
     }else{
         $('#announcement').append("<div> </div>");
     }
 });
</code>```

Title: Append data to div using jquery

Body:
Can I know how can we append the title and message to the div using jquery for every row? The issue with my code is that each of the data is not being displayed in a row.

Topic

Body:
Looks to me like your markup isn't going to work very well if you're working with a collection of records. What you're likely to end up with the way you're going is something like...

<!-- Title1
     Title2
     Message1
     Message2 -->

Change your code up a little so that you can add to the markup for each record:

 $.ajax({
     url: '/test/back-api/admin/announcements',
     method: 'GET',
     success: function(d){
     if(d.result){
         var posts = d.data;
         for(var i=0; i < posts.length; i++){
         var post = posts[i];

         var Title = "<div class=\"title\">" + post.title + "</div>";
         var Message = "<div class=\"message\">" + post.message + "</div>";
         $('#announcement').append(Title, Message);
     }else{
         $('#announcement').append("<div> </div>");
     }
 });


问:
Can't copy oci.dll file to C:/windows/system32
As it's an ancient problem, still couldn't find good solutions for that.

I am using cmd to copy oci.dll to system32 folder.

Access is denied is showing. My all oracle services have been stopped and I am logged in a administrator account.

And as expected, I couldn't delete the oci.dll file as well.

答:
Finally I am able to solve this problem. I am posting the solution step by step as it might be helpful in future.

Reason of the problem:

The problem is that the file oci.dll which I want to copy or delete is already been fetched by one/more processes.

Solution:

1) Firstly, we have to figure out which process(s) is/are actually using oci.dll file. To check this simply go to cmd, change directory to C:\Documents and Settings, and then run tasklist/m oci.dll(or the name of the dll you facing troubles. So, in short:

```<code>C:\Documents and Settings>tasklist /m oci.dll
</code>```

Running this command you can get a list of process(es) with PID which are using oci.dll. In my case it was-  exploerer.exe

So, I have to kill the explorer.exe process to copy/delete oci.dll file. A very good software Process Exploerer of Microsoft could also be used for finding process regarding the .dll files and kill the processes as well.

Now, we're all set. We have to open cmd in Administrator mode and copy the oci.dll file to system32 foler.And oci.dll has been copied successfully.

P.S.

Ending explorer.exe you may find problems for copying. After properly killing all the explorer.exe process you may press Ctrl+Alt+Delete to open taskmanager  and go File -> New Task(Run... ) to create a new task for explorer to copy/delete.

Body:
Finally I am able to solve this problem. I am posting the solution step by step as it might be helpful in future.

Reason of the problem:

The problem is that the file oci.dll which I want to copy or delete is already been fetched by one/more processes.

Solution:

1) Firstly, we have to figure out which process(s) is/are actually using oci.dll file. To check this simply go to cmd, change directory to C:\Documents and Settings, and then run tasklist/m oci.dll(or the name of the dll you facing troubles. So, in short:

C:\Documents and Settings>tasklist /m oci.dll

Running this command you can get a list of process(es) with PID which are using oci.dll. In my case it was-  exploerer.exe

So, I have to kill the explorer.exe process to copy/delete oci.dll file. A very good software Process Exploerer of Microsoft could also be used for finding process regarding the .dll files and kill the processes as well.

Now, we're all set. We have to open cmd in Administrator mode and copy the oci.dll file to system32 foler.And oci.dll has been copied successfully.

P.S.

Ending explorer.exe you may find problems for copying. After properly killing all the explorer.exe process you may press Ctrl+Alt+Delete to open taskmanager  and go File -> New Task(Run... ) to create a new task for explorer to copy/delete.


问:
Loading data from a (MySQL) database into Django without models
This might sound like a bit of an odd question - but is it possible to load data from a (in this case MySQL) table to be used in Django without the need for a model to be present?

I realise this isn't really the Django way, but given my current scenario, I don't really know how better to solve the problem.

I'm working on a site, which for one aspect makes use of a table of data which has been bought from a third party. The columns of interest are liklely to remain stable, however the structure of the table could change with subsequent updates to the data set. The table is also massive (in terms of columns) - so I'm not keen on typing out each field in the model one-by-one. I'd also like to leave the table intact - so coming up with a model which represents the set of columns I am interested in is not really an ideal solution.

Ideally, I want to have this table in a database somewhere (possibly separate to the main site database) and access its contents directly using SQL.

答: There is one feature called  inspectdb in Django. for legacy databases like MySQL , it creates models automatically by inspecting your db tables. it stored in our app files as models.py. so we don't need to type all column manually.But read the documentation carefully before creating the models because it may affect the DB data ...i hope this will be useful for you.


问:
Human body detection using OpenCV in Android
I want to create an Android application in which i want to detect human body from an image. I haven't started coding yet(its just an idea), so i am not able to show you any codes. I heard about OpenCV face detection for android.
I have tried to use OpenCV face detection, But since i am newbie in android, i am not able to do so.

My question is "Is there anything in OpenCV that can help me to detect whole human body rather than just face?", if YES then "is there any tutorials regarding this?"

thanks for HELP in advance.

答:
Yes, it is possible to detect the human body in the form of images or videos using OpenCV, follow the steps below in order to start:

Step1

Create a new OpenCV project in Android Studio. In this tutorial, it explains how to create a new OpenCV project in Android Studio.

Step2

The following links explain Human detection using OpenCV:

HOG Person Detector Tutorial

People Detection in OpenCV


问:
Comparing objects
I have a class it contains some string members, some double members and some array objects.

I create two objects of this class, is there any simplest, efficient way of comparing these objects and say their equal? Any suggestions?

I know how to write a compare function, but will it be time consuming.

答:
The best answer is to implement IEquatable for your class - it may not be the answer you want to hear, but that's the best way to implement value equivalence in .NET.

Another option would be computing a unique hash of all of the members of your class and then doing value comparisons against those, but that's even more work than writing a comparison function ;)

Title: Comparing objects


问:
Grails - No signature of method is applicable for argument types
I'm starting with Grails (using mainly the Eclipse plugin) and have been having trouble with Grails reading Java src files - whether it's a jar in the bin folder, or a Java file in the src/java folder.

I've created an example of how I call from my controller, a Java static method, and for some reason there is a problem with the argument type. Here's the controller:

```<code>def attempt = {
    int counter = 20
    int val1 = 1
    int val2 = 1
    def list = Replicate.create(counter, val1, val2)
    render list.size()
}
</code>```

And here is the Java file in the src/Java folder:

```<code>public class Replicate {

public static LinkedList<Pair<Integer, Integer>> create (int count, int val1, int val2){

    LinkedList<Pair<Integer, Integer>> list = new LinkedList<Pair<Integer,Integer>>();

    for (int i = 0; i < count; i++){
        list.add(new Pair<Integer, Integer>(val1, val2));
    }

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

When I try and load the page for the Controller's method, I get:

```<code>URI:
/clive-toolbox/cliveServices/attempt
Class:
groovy.lang.MissingMethodException
Message:
No signature of method: static tst.Replicate.create() is applicable for argument types:     (java.lang.Integer, java.lang.Integer, java.lang.Integer) values: [20, 1, 1] Possible solutions:     grep(), iterator()
</code>```

The line that is highlighted as the error is this (in the controller):

```<code>def list = Replicate.create(counter, val1, val2)
</code>```

And in other cases, working the same way, Grails manages to compile the project but just doesn't execute the method. I assume I'm doing something wrong. Any ideas here?

答:
I received the same error when trying to call a service method from a controller.

What I did wrong was that I had not typed: "servicename" at the top of the method in the controller where I called the service from.

Body:
I'm starting with Grails (using mainly the Eclipse plugin) and have been having trouble with Grails reading Java src files - whether it's a jar in the bin folder, or a Java file in the src/java folder.

I've created an example of how I call from my controller, a Java static method, and for some reason there is a problem with the argument type. Here's the controller:

def attempt = {
    int counter = 20
    int val1 = 1
    int val2 = 1
    def list = Replicate.create(counter, val1, val2)
    render list.size()
}

And here is the Java file in the src/Java folder:

public class Replicate {

public static LinkedList<Pair<Integer, Integer>> create (int count, int val1, int val2){

    LinkedList<Pair<Integer, Integer>> list = new LinkedList<Pair<Integer,Integer>>();

    for (int i = 0; i < count; i++){
        list.add(new Pair<Integer, Integer>(val1, val2));
    }

    return list;
}
}

When I try and load the page for the Controller's method, I get:

URI:
/clive-toolbox/cliveServices/attempt
Class:
groovy.lang.MissingMethodException
Message:
No signature of method: static tst.Replicate.create() is applicable for argument types:     (java.lang.Integer, java.lang.Integer, java.lang.Integer) values: [20, 1, 1] Possible solutions:     grep(), iterator()

The line that is highlighted as the error is this (in the controller):

def list = Replicate.create(counter, val1, val2)

And in other cases, working the same way, Grails manages to compile the project but just doesn't execute the method. I assume I'm doing something wrong. Any ideas here?


问:
Spacing between currency symbol and value: iOS swift 3
I am having an app with IAP. I need to show the prices with values based on location. I have made till this. Now I am able to display the prices based on location.

However, I need some spacing between currency symbol and the value.
i.e, I need $ 9.99 (currently it shows $9.99).

FYI: I am getting the price from itunes (used a variable to get the price got from itunes and displaying it in a textview).

I have followed this without success: NSNumberFormatter paddingPosition doesn't work

I have also referred this, but it does not work as well:
Swift 3 and NumberFormatter (.currency) == ¤?

Any suggestions?

I am doing this:

```<code>var index: Int = 0 {
    didSet {

        var monthlyValue = String()

        if prefs.value(forKey: "monthly") != nil {

            monthlyValue = prefs.value(forKey: "monthly") as! String

        }

        let subcharges : Array<String>   = ["Free but limited just to get started","or \(monthlyValue) Billed Monthly",""]

        let yearlypermonth = Int()

        var mycurrency1 = String()

        if prefs.value(forKey: "yearly") != nil {

            let yearlyvalue = prefs.value(forKey: "yearly") as! String

            print("wallet view yearlyvalue: \(yearlyvalue)")

            let firstProduct  = StoreManager.shared.productsFromStore[0]

            if let mycurrency = firstProduct.priceLocale.currencySymbol {

                print("mycurrency: \(mycurrency)")

                mycurrency1 = mycurrency
                prefs.set(mycurrency, forKey: "mycurrency")

            }

            let formatter = NumberFormatter()
            formatter.numberStyle = .currency
//                formatter.paddingPosition = .afterPrefix
//
//                //formatter.locale = Locale(identifier: "en_US")
//                formatter.paddingCharacter = " "
//                formatter.formatWidth = 7

            let number1 = formatter.number(from: yearlyvalue)

            print("wallet view number1: \(number1)")

            let secondProd = StoreManager.shared.productsFromStore[1]

            let numberFormatter = NumberFormatter()
//                numberFormatter.paddingPosition = .afterPrefix
//                numberFormatter.paddingCharacter = " "
//                numberFormatter.formatWidth = 7
            // Get its price from iTunes Connect
            numberFormatter.locale = secondProd.priceLocale
            let price2Str = numberFormatter.string(from: secondProd.price)

            let currencynumbers2 =  secondProd.price.doubleValue / 12

            monthonValueforaYear = String(format: "%.2f", currencynumbers2)

            print("walletview VC monthonValueforaYear: \(monthonValueforaYear)")

            //prefs.set(price2Str, forKey: "yearly")
            prefs.set(monthonValueforaYear, forKey: "monthonValueforaYear")

        }
        var charges : Array<String> = ["\(mycurrency1) 0/m","\(mycurrency1 + monthonValueforaYear)/m","Coming Soon"]

        print("wallet view charges: \(charges)")

        self.Headingtitle.text    = Headingarray[index]
        self.planchargelabel.text  = charges[index]
        self.subchargelabel.text = subcharges[index]
</code>```

Interestingly, for subchargelabel value, I get a little spacing

The commented section was uncommented while I tried running the app. Just so you know it

Thanks for your help!

答:
Just putting symbol, space, and amount is not a good idea. It's sequence may differ by locale or currency. Following method will give you an answer.

```<code>func customFormattedAmountString(amount: Int) -> String? {
    let formatter = NumberFormatter()
    formatter.numberStyle = .currency
    formatter.locale = Locale.current

    if let amountString = formatter.string(from: NSNumber(value: amount)) {
        // check if it has default space like EUR
        let hasSpace = amountString.rangeOfCharacter(from: .whitespaces) != nil

        if let indexOfSymbol = amountString.characters.index(of: Character(formatter.currencySymbol)) {
            if amountString.startIndex == indexOfSymbol {
                formatter.paddingPosition = .afterPrefix
            } else {
                formatter.paddingPosition = .beforeSuffix
            }
        }
        if !hasSpace {
            formatter.formatWidth = amountString.characters.count + 1
            formatter.paddingCharacter = " "
        }
    } else {
        print("Error while making amount string from given amount: \(amount)")
        return nil
    }

    if let finalAmountString = formatter.string(from: NSNumber(value: amount)) {
        return finalAmountString
    } else {
        return nil
    }
}
</code>```

Use it as below,

```<code>if let formattedAmount = customFormattedAmountString(amount: 5000000) {
    print(formattedAmount)
}
</code>```

That will print out dollar,

```<code>$ 5,000,000.00
</code>```

and Euro,

```<code>5.000.000,00 €
</code>```

As you wanted to have space between currency symbol and amount. If you just append string like first answer, you'll get "€ 5.000.000,00", not a desired one - "5.000.000,00 €".

Body:
I am having an app with IAP. I need to show the prices with values based on location. I have made till this. Now I am able to display the prices based on location.

However, I need some spacing between currency symbol and the value.
i.e, I need $ 9.99 (currently it shows $9.99).

FYI: I am getting the price from itunes (used a variable to get the price got from itunes and displaying it in a textview).

I have followed this without success: NSNumberFormatter paddingPosition doesn't work

I have also referred this, but it does not work as well:
Swift 3 and NumberFormatter (.currency) == ¤?

Any suggestions?

I am doing this:

var index: Int = 0 {
    didSet {

        var monthlyValue = String()

        if prefs.value(forKey: "monthly") != nil {

            monthlyValue = prefs.value(forKey: "monthly") as! String

        }

        let subcharges : Array<String>   = ["Free but limited just to get started","or \(monthlyValue) Billed Monthly",""]

        let yearlypermonth = Int()

        var mycurrency1 = String()

        if prefs.value(forKey: "yearly") != nil {

            let yearlyvalue = prefs.value(forKey: "yearly") as! String

            print("wallet view yearlyvalue: \(yearlyvalue)")

            let firstProduct  = StoreManager.shared.productsFromStore[0]

            if let mycurrency = firstProduct.priceLocale.currencySymbol {

                print("mycurrency: \(mycurrency)")

                mycurrency1 = mycurrency
                prefs.set(mycurrency, forKey: "mycurrency")

            }

            let formatter = NumberFormatter()
            formatter.numberStyle = .currency
//                formatter.paddingPosition = .afterPrefix
//
//                //formatter.locale = Locale(identifier: "en_US")
//                formatter.paddingCharacter = " "
//                formatter.formatWidth = 7

            let number1 = formatter.number(from: yearlyvalue)

            print("wallet view number1: \(number1)")

            let secondProd = StoreManager.shared.productsFromStore[1]

            let numberFormatter = NumberFormatter()
//                numberFormatter.paddingPosition = .afterPrefix
//                numberFormatter.paddingCharacter = " "
//                numberFormatter.formatWidth = 7
            // Get its price from iTunes Connect
            numberFormatter.locale = secondProd.priceLocale
            let price2Str = numberFormatter.string(from: secondProd.price)

            let currencynumbers2 =  secondProd.price.doubleValue / 12

            monthonValueforaYear = String(format: "%.2f", currencynumbers2)

            print("walletview VC monthonValueforaYear: \(monthonValueforaYear)")

            //prefs.set(price2Str, forKey: "yearly")
            prefs.set(monthonValueforaYear, forKey: "monthonValueforaYear")

        }
        var charges : Array<String> = ["\(mycurrency1) 0/m","\(mycurrency1 + monthonValueforaYear)/m","Coming Soon"]

        print("wallet view charges: \(charges)")

        self.Headingtitle.text    = Headingarray[index]
        self.planchargelabel.text  = charges[index]
        self.subchargelabel.text = subcharges[index]

Interestingly, for subchargelabel value, I get a little spacing

The commented section was uncommented while I tried running the app. Just so you know it

Thanks for your help!

Body:
Just putting symbol, space, and amount is not a good idea. It's sequence may differ by locale or currency. Following method will give you an answer.

func customFormattedAmountString(amount: Int) -> String? {
    let formatter = NumberFormatter()
    formatter.numberStyle = .currency
    formatter.locale = Locale.current

    if let amountString = formatter.string(from: NSNumber(value: amount)) {
        // check if it has default space like EUR
        let hasSpace = amountString.rangeOfCharacter(from: .whitespaces) != nil

        if let indexOfSymbol = amountString.characters.index(of: Character(formatter.currencySymbol)) {
            if amountString.startIndex == indexOfSymbol {
                formatter.paddingPosition = .afterPrefix
            } else {
                formatter.paddingPosition = .beforeSuffix
            }
        }
        if !hasSpace {
            formatter.formatWidth = amountString.characters.count + 1
            formatter.paddingCharacter = " "
        }
    } else {
        print("Error while making amount string from given amount: \(amount)")
        return nil
    }

    if let finalAmountString = formatter.string(from: NSNumber(value: amount)) {
        return finalAmountString
    } else {
        return nil
    }
}

Use it as below,

if let formattedAmount = customFormattedAmountString(amount: 5000000) {
    print(formattedAmount)
}

That will print out dollar,

$ 5,000,000.00

and Euro,

5.000.000,00 €

As you wanted to have space between currency symbol and amount. If you just append string like first answer, you'll get "€ 5.000.000,00", not a desired one - "5.000.000,00 €".


问:
magento top link changes
I am new to Magento. I have downloaded a theme in Magento and trying to change the top links. I couldn't track the files. How do i change the toplinks in Magento theme.

答:
If you want to know the file loacation then you can use magento default template path hint feature. Check given below URL.

http://excellencemagentoblog.com/blog/2011/09/07/magento-template-path-hints-magento/

Title: magento top link changes


问:
trying to delete files on WinSCP that have the owner Apache
WINSCP error: Permission denied. Error code: 3 Error message from server: Permission denied.

I created 11 folders with 1 picture in each of them while I was testing my website. I am now trying to delete those folders on WINSCP but I receive the error written above. The folders were created using a PHP script on my codeigniter application. The folders are created when a user is logged into the codeigniter application, and completes a form.
I created the folder using the function: mkdir( $path ).
I copyed the image into the folder using the function: copy( $pic , $path).
On WinSCP the folders and pictures have the owner apache.

How can I delete the folders now? From what I understand I cannot delete the folders on WinSCP because I am logged into my personal account, not apache. I tried to make a link on my web application which changes permissions on a folder and login as the user account that created the folders. This returns me the codeignter error "chown: Operation not permitted".

So how can I delete the folders as the apache owner? Do I need to use the WinSCP console?

I found out how to delete these folders. I made a delete component for my application. When the component was finished i logged in and used the delete component. This allowed me to delete the folders.

答:
Well as I understand, you are trying to delete folders while logged in with your personal account, but the folders are owned by apache user. There are several possible solutions for your problem.

One of them as suggested in the comment, is to login to WinSCP as root user.

Another option is to add your personal account to the apache group. If the folder that you want to delete is writable by group then you should be able to delete the folder

Another option is to run apache and php under your personal account.


问:
How to make script file to run several commands on several terminals in ubuntu?
I have to open three terminals and each terminal should go to three directories and need to run three files on those three terminals. Now I need  speed up my task. Beacuse of that need to do it by running a single script file.How can  I do that?

As a example I have to run those three commands on three terminals. But I need to do those thing using one single file running.

```<code>cd /home/xyz/Desktop/project/components/core;
python3 Main.py

aria2c --enable-rpc

cd /home/xyz/Desktop/project/ui;
gulp serve
</code>```

答:
One of my friends suggested this as an answer and it worked for me.I can run those terminal commands with & operator and then those commands run on background and they will run on the same terminal without any failure.I created a single file using below commands and when I run it, that file prompt to run those commands in same terminal.

!/bin/bash

cd /home/xyz/Desktop/project/components/core;python3 main.py  &
aria2c --enable-rpc &
cd /home/kaveesh/Desktop/project/ui;gulp serve &

Body:
I have to open three terminals and each terminal should go to three directories and need to run three files on those three terminals. Now I need  speed up my task. Beacuse of that need to do it by running a single script file.How can  I do that?

As a example I have to run those three commands on three terminals. But I need to do those thing using one single file running.

cd /home/xyz/Desktop/project/components/core;
python3 Main.py

aria2c --enable-rpc

cd /home/xyz/Desktop/project/ui;
gulp serve