问:
Bind Command for MenuItem in DataTemplate without Tag
I want to bind a command in my ViewModel to a menuItem which is in DataTemplate. I can do that with using Tag. Is there any method which can do the same task but without using tag.

```<code><Window.Resources>
    <DataTemplate x:Key="StudentListBoxItemTemplate">
        <StackPanel Tag="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}">
            <TextBlock Text="{Binding Name}"/>
            <StackPanel.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Trigger" Command="{Binding PlacementTarget.Tag.TriggerCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
                </ContextMenu>
            </StackPanel.ContextMenu>
        </StackPanel>
    </DataTemplate>
</Window.Resources>
<StackPanel>
    <ListBox
        ItemsSource="{Binding StudentList}"
        ItemTemplate="{StaticResource StudentListBoxItemTemplate}">
    </ListBox>
</StackPanel>
</code>```

My ViewModel

```<code>public class MainViewModel {
    public ICommand TriggerCommand { ... }
    public ObservableList<Student> StudentList { ... }
}
</code>```

答:
You can try to add click event to the menuItem like following

```<code><Menu Style="{StaticResource bellRingersFontStyle}" Height="23" Name="menu1" Width="Auto" DockPanel.Dock="Top" VerticalAlignment="Top">
            <MenuItem Header="_File">
                <MenuItem Header="_New Member" Name="newMember" Click="newMember_Click" >
                    <MenuItem.Icon>
                        <Image Source="Face.bmp" />
                    </MenuItem.Icon>
                </MenuItem>
                <MenuItem Header="_Save Member Details" Name="saveMember" IsEnabled="False" Click="saveMember_Click">
                    <MenuItem.Icon>
                        <Image Source="Note.bmp" />
                    </MenuItem.Icon>
                </MenuItem>
                <Separator />
                <MenuItem Header="E_xit" Name="exit" Click="exit_Click"  />
            </MenuItem>
            <MenuItem Header="_Help">
                <MenuItem Header="_About Middleshire Bell Ringers" Name="about" Click="about_Click" >
                    <MenuItem.Icon>
                        <Image Source="Ring.bmp" />
                    </MenuItem.Icon>
                </MenuItem>
            </MenuItem>
        </Menu>
</code>```

Try binding the command to Click. My VS is down so can't check at this moment.

Body:
I want to bind a command in my ViewModel to a menuItem which is in DataTemplate. I can do that with using Tag. Is there any method which can do the same task but without using tag.

<Window.Resources>
    <DataTemplate x:Key="StudentListBoxItemTemplate">
        <StackPanel Tag="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}">
            <TextBlock Text="{Binding Name}"/>
            <StackPanel.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Trigger" Command="{Binding PlacementTarget.Tag.TriggerCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
                </ContextMenu>
            </StackPanel.ContextMenu>
        </StackPanel>
    </DataTemplate>
</Window.Resources>
<StackPanel>
    <ListBox
        ItemsSource="{Binding StudentList}"
        ItemTemplate="{StaticResource StudentListBoxItemTemplate}">
    </ListBox>
</StackPanel>

My ViewModel

public class MainViewModel {
    public ICommand TriggerCommand { ... }
    public ObservableList<Student> StudentList { ... }
}

Body:
You can try to add click event to the menuItem like following

<Menu Style="{StaticResource bellRingersFontStyle}" Height="23" Name="menu1" Width="Auto" DockPanel.Dock="Top" VerticalAlignment="Top">
            <MenuItem Header="_File">
                <MenuItem Header="_New Member" Name="newMember" Click="newMember_Click" >
                    <MenuItem.Icon>
                        <Image Source="Face.bmp" />
                    </MenuItem.Icon>
                </MenuItem>
                <MenuItem Header="_Save Member Details" Name="saveMember" IsEnabled="False" Click="saveMember_Click">
                    <MenuItem.Icon>
                        <Image Source="Note.bmp" />
                    </MenuItem.Icon>
                </MenuItem>
                <Separator />
                <MenuItem Header="E_xit" Name="exit" Click="exit_Click"  />
            </MenuItem>
            <MenuItem Header="_Help">
                <MenuItem Header="_About Middleshire Bell Ringers" Name="about" Click="about_Click" >
                    <MenuItem.Icon>
                        <Image Source="Ring.bmp" />
                    </MenuItem.Icon>
                </MenuItem>
            </MenuItem>
        </Menu>

Try binding the command to Click. My VS is down so can't check at this moment.


来源: stackexchange

问:
Conditionals won't work
Okay so me and my friend are programming a small basic torture game and when I try to run my part of the code, some of the if/elif it will not run as if they were False when they seem True

```<code>lives = 5
lives_1 = 13
random_number = random.randint(0,100)
random_number_1 = random.randit(0,1000)
        while lives > 0:
            print random_number # delete in final product
            print "'You have %d chances to save your partner'" % (lives)
            guess_0 = int(raw_input("Guess a number from 1 to 100 "))
            print "You have guessed %d" % (guess_0)
            proceed_2 = raw_input("Press 'Enter' to proceed")
            if guess_0 != random_number: # This works
                print "It is incorrect, your partner loses a finger"
                lives -= 1
                continue
            elif guess_0 == random_number: # This works
                print "It is correct you and your partner get to walk free"
                print "GAME OVER"
                break
            elif guess > random_number: # Doesn't work
                print "'LOWER!'"
            elif guess < random_number: # Doesn't work
                print "'HIGHER!'"
        else:
            print "GAME OVER"

    while lives_1 > 0:
        print random_number_1 # delete in final product
        print "'You ha-- %d ch---e-'" % (lives_1)
        guess_1 = raw_input("What should you do? ")
        proceed_1 = raw_input("Press Enter to proceed")
        print "You decided to shout {}".format(guess_1)
        if guess_1 == random_number_1:
            print "The cult has decided to let you go" # doesn't work
            break
        elif guess_1 != random_number_1: # Works but also works when false
            lives_1 -= 1
            if lives_1 < 5:
                print "Tears begin to blind you as you're nearing death"
            continue
        elif guess_1 < random_number_1: # doesn't work
            print "You squeel in agony as one of your nails were ripped off"
            print "'Higher'"
        elif guess_1 > random_number_1: #doesn't work
            print "You squeel in agony as one of your nails were ripped off"
            print "'LOWER...'"
    else:
        print "GAME OVER"
</code>```

I want it to print out larger or larger than 3 but as you can see it won't. I have the same problem with the other one.

For the second while function, when I enter a number lower or larger than random_number(_1) it won't print out larger or lower and if I enter the value for random_number(_1) it won't run. I can't see anything wrong please help

答:
The problem here ist that your condition

```<code>guess > random_number
</code>```

is an else if of

```<code>guess_0 != random_number
</code>```

and

```<code>guess_0 == random_number
</code>```

meaning it will only get evaluated if NONE of the former two have evaluated to True. As you can see this cannot be the case. You can instead write it like this:

```<code>        if guess_0 == random_number:
            print "It is correct you and your partner get to walk free"
            print "GAME OVER"
            break
        if guess_0 != random_number:
            print "It is incorrect, your partner loses a finger"
            lives -= 1
            if guess > random_number:
                print "'LOWER!'"
            elif guess < random_number:
                print "'HIGHER!'"
</code>```

In your second while loop you should edit the line

```<code>guess_1=raw_input(....)
</code>```

to

```<code>guess_1=int(raw_input(....))
</code>```

ContentLicense: CC BY-SA 3.0

Title: Conditionals won't work

Body:
Okay so me and my friend are programming a small basic torture game and when I try to run my part of the code, some of the if/elif it will not run as if they were False when they seem True

lives = 5
lives_1 = 13
random_number = random.randint(0,100)
random_number_1 = random.randit(0,1000)
        while lives > 0:
            print random_number # delete in final product
            print "'You have %d chances to save your partner'" % (lives)
            guess_0 = int(raw_input("Guess a number from 1 to 100 "))
            print "You have guessed %d" % (guess_0)
            proceed_2 = raw_input("Press 'Enter' to proceed")
            if guess_0 != random_number: # This works
                print "It is incorrect, your partner loses a finger"
                lives -= 1
                continue
            elif guess_0 == random_number: # This works
                print "It is correct you and your partner get to walk free"
                print "GAME OVER"
                break
            elif guess > random_number: # Doesn't work
                print "'LOWER!'"
            elif guess < random_number: # Doesn't work
                print "'HIGHER!'"
        else:
            print "GAME OVER"

    while lives_1 > 0:
        print random_number_1 # delete in final product
        print "'You ha-- %d ch---e-'" % (lives_1)
        guess_1 = raw_input("What should you do? ")
        proceed_1 = raw_input("Press Enter to proceed")
        print "You decided to shout {}".format(guess_1)
        if guess_1 == random_number_1:
            print "The cult has decided to let you go" # doesn't work
            break
        elif guess_1 != random_number_1: # Works but also works when false
            lives_1 -= 1
            if lives_1 < 5:
                print "Tears begin to blind you as you're nearing death"
            continue
        elif guess_1 < random_number_1: # doesn't work
            print "You squeel in agony as one of your nails were ripped off"
            print "'Higher'"
        elif guess_1 > random_number_1: #doesn't work
            print "You squeel in agony as one of your nails were ripped off"
            print "'LOWER...'"
    else:
        print "GAME OVER"

I want it to print out larger or larger than 3 but as you can see it won't. I have the same problem with the other one.

For the second while function, when I enter a number lower or larger than random_number(_1) it won't print out larger or lower and if I enter the value for random_number(_1) it won't run. I can't see anything wrong please help

Body:
The problem here ist that your condition

guess > random_number

is an else if of

guess_0 != random_number

and

guess_0 == random_number

meaning it will only get evaluated if NONE of the former two have evaluated to True. As you can see this cannot be the case. You can instead write it like this:

        if guess_0 == random_number:
            print "It is correct you and your partner get to walk free"
            print "GAME OVER"
            break
        if guess_0 != random_number:
            print "It is incorrect, your partner loses a finger"
            lives -= 1
            if guess > random_number:
                print "'LOWER!'"
            elif guess < random_number:
                print "'HIGHER!'"

In your second while loop you should edit the line

guess_1=raw_input(....)

to

guess_1=int(raw_input(....))


问:
Plugins on nodejs across multiple apps , what package to use? (With wordpress in mind)
I am concurrently writing a few apps which use "plugins" that can be run separately and independently on a nodejs/mongo platform. These apps use independent models for mongo collections, routes and views (MVC).

My question: what package should I use to manage this Github/npm or other ?

More info : Ideally I would like to edit one plugin and through "github/npm " they would all be modified. What is suggested to manage this? Github seems limited with this and would like to make sure that npm is the right choice before modifying code to make this work.

Thanks a million!

Body:
Aftere some playing around , the NPM package manager seems best ,

///////////////////////////////////////////////
////       FRATERNATE NPM MODULE          ////
/////////////////////////////////////////////
var fraternate = require("fraternate");
app.use('/', fraternate);


问:
Very slow: ActiveRecord::QueryCache#call
I have an app on heroku, running on Puma:

```<code>workers 2
threads_count 3
pool 5
</code>```

It looks like some requests get stuck in the middleware, and it makes the app very slow (VERY!).
I have seen other people threads about this problem but no solution so far.

Please let me know if you have any hint.

!

!

答:
I will answer my own question:
I simply had to check all queries to my DB. One of them was taking a VERY long time, and even if it was not requested often, it would slow down the whole server for quite some time afterwards(even after the process was done, there was a sort of "traffic jam" on the server).
Solution:
Check all the queries to your database, fix the slowest ones (it might simply mean breaking it down in few steps, it might mean make it run at night when there is no traffic, etc...).
Once this queries are fixed, everything should go back to normal.</p>

Body:
I have an app on heroku, running on Puma:

workers 2
threads_count 3
pool 5

It looks like some requests get stuck in the middleware, and it makes the app very slow (VERY!).
I have seen other people threads about this problem but no solution so far.

Please let me know if you have any hint.

!

!


答:
You can use _.forOwn() to loop over your object properties, _.map() to loop over each array items and use momentjs to change the item format.

This is how should be your code:

```<code>_.forOwn(obj, function(value, key) {
   obj[key] = _.map(value, function(item) {
      return moment(item).format("HH:mm");
   });
});
</code>```

Demo:

var obj = {
  "2017-12-08": [
    "2017-12-08T13:00:00+0530",
    "2017-12-08T15:00:00+0530",
    "2017-12-08T15:30:00+0530",
    "2017-12-08T16:00:00+0530"
  ],
  "2017-12-09": [
    "2017-12-09T09:00:00+0530",
    "2017-12-09T09:30:00+0530",
    "2017-12-09T10:00:00+0530"
  ],
  "2017-12-10": [
    "2017-12-10T09:00:00+0530",
    "2017-12-10T09:30:00+0530",
    "2017-12-10T10:00:00+0530",
    "2017-12-10T10:30:00+0530"
  ]
};

_.forOwn(obj, function(value, key) {
  obj[key] = _.map(value, function(item) {
    return moment(item).format("HH:mm");
  });
});

console.log(obj);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js"></script></code>```

Title: Changing time format in an array using moment and angularjs and lodash

Body:
I have Json data which has timings based on dates.

obj = {
"2017-12-08": [
    "2017-12-08T13:00:00+0530",
    "2017-12-08T15:00:00+0530",
    "2017-12-08T15:30:00+0530",
    "2017-12-08T16:00:00+0530"
],
"2017-12-09": [
    "2017-12-09T09:00:00+0530",
    "2017-12-09T09:30:00+0530",
    "2017-12-09T10:00:00+0530"
],
"2017-12-10": [
    "2017-12-10T09:00:00+0530",
    "2017-12-10T09:30:00+0530",
    "2017-12-10T10:00:00+0530",
    "2017-12-10T10:30:00+0530"
]
}

I want to convert this json object into the format below:

obj = {
"2017-12-08": ["13:00","15:00","15:30","16:00"],
"2017-12-09": ["09:00","09:30","10:00"],
"2017-12-10": ["09:00","09:30","10:00","10:30"]
}

Currently I'm using a for loop to traverse through each element in the array and then replace each element using

obj[Object.keys(obj)[date]][time]=moment(obj[Object.keys(obj)[date]][time]).format(HH:mm);

how do i accomplish this using lodash , moment and angularjs?

Body:
You can use _.forOwn() to loop over your object properties, _.map() to loop over each array items and use momentjs to change the item format.

This is how should be your code:

_.forOwn(obj, function(value, key) {
   obj[key] = _.map(value, function(item) {
      return moment(item).format("HH:mm");
   });
});

Demo:

var obj = {
  "2017-12-08": [
    "2017-12-08T13:00:00+0530",
    "2017-12-08T15:00:00+0530",
    "2017-12-08T15:30:00+0530",
    "2017-12-08T16:00:00+0530"
  ],
  "2017-12-09": [
    "2017-12-09T09:00:00+0530",
    "2017-12-09T09:30:00+0530",
    "2017-12-09T10:00:00+0530"
  ],
  "2017-12-10": [
    "2017-12-10T09:00:00+0530",
    "2017-12-10T09:30:00+0530",
    "2017-12-10T10:00:00+0530",
    "2017-12-10T10:30:00+0530"
  ]
};

_.forOwn(obj, function(value, key) {
  obj[key] = _.map(value, function(item) {
    return moment(item).format("HH:mm");
  });
});

console.log(obj);

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment.min.js"></script>


问:
I've kept a class and its members from Proguards obfuscation, but a static final member is obfuscated?
I have this class

```<code>public class MyClass extends StringType implements ProtectedAgainstProguard {

    private static final String delimiter = "#";
    private static final MyClass singleton = new MyClass ();

    private MyClass() {
        super(someStuff);
    }

    public static MyClass getSingleton() {
        return singleton;
    }

    @Override
    public Object someMethodA() {

    }

    @Override
    public Object someMethodB() {

    }
}
</code>```

Here's my ProGuard config:

```<code>-keep public interface com.example.android.application.ProtectedAgainstProguard
-keep public class * implements com.example.android.application.ProtectedAgainstProguard
-keep class * implements com.example.android.application.ProtectedAgainstProguard
-keep public class * extends com.example.android.application.ProtectedAgainstProguard
-keep class * extends com.example.android.application.ProtectedAgainstProguard
</code>```

and here is the mapping.txt for this class

```<code>com.example.android.domain.MyClass -> com.example.android.domain.MyClass :
    com.example.android.domain.MyClass singleton -> a
    15:16:void <init>() -> <init>
    24:28:java.lang.Object someMethodA() -> someMethodA
    34:38:java.lang.Object someMethodB() -> someMethodB
    12:12:void <clinit>() -> <clinit>
</code>```

As you can see the static final singleton (dont know if its the member or the method, I think its the method, is obfuscated.
How do I tell proguard to just keep its hands off the entire class and everything in it?
I don't want to list particular classes and their particular methods/members that I want to keep, I just want a general rule that says "don't do ANYTHING to a class that implements ProtectedAgainstProguard "

答:
Turns out in order to protect the members of the class, we need to add { *; } at the end of the rule - because keep isn't very useful by itself.

```<code>-keep public interface com.example.android.application.ProtectedAgainstProguard { *; }
-keep public class * implements com.example.android.application.ProtectedAgainstProguard { *; }
-keep class * implements com.example.android.application.ProtectedAgainstProguard { *; }
-keep public class * extends com.example.android.application.ProtectedAgainstProguard { *; }
-keep class * extends com.example.android.application.ProtectedAgainstProguard { *; }
</code>```

Body:
I have this class

public class MyClass extends StringType implements ProtectedAgainstProguard {

    private static final String delimiter = "#";
    private static final MyClass singleton = new MyClass ();

    private MyClass() {
        super(someStuff);
    }

    public static MyClass getSingleton() {
        return singleton;
    }

    @Override
    public Object someMethodA() {

    }

    @Override
    public Object someMethodB() {

    }
}

Here's my ProGuard config:

-keep public interface com.example.android.application.ProtectedAgainstProguard
-keep public class * implements com.example.android.application.ProtectedAgainstProguard
-keep class * implements com.example.android.application.ProtectedAgainstProguard
-keep public class * extends com.example.android.application.ProtectedAgainstProguard
-keep class * extends com.example.android.application.ProtectedAgainstProguard

and here is the mapping.txt for this class

com.example.android.domain.MyClass -> com.example.android.domain.MyClass :
    com.example.android.domain.MyClass singleton -> a
    15:16:void <init>() -> <init>
    24:28:java.lang.Object someMethodA() -> someMethodA
    34:38:java.lang.Object someMethodB() -> someMethodB
    12:12:void <clinit>() -> <clinit>

As you can see the static final singleton (dont know if its the member or the method, I think its the method, is obfuscated.
How do I tell proguard to just keep its hands off the entire class and everything in it?
I don't want to list particular classes and their particular methods/members that I want to keep, I just want a general rule that says "don't do ANYTHING to a class that implements ProtectedAgainstProguard "

Body:
Turns out in order to protect the members of the class, we need to add { *; } at the end of the rule - because keep isn't very useful by itself.

-keep public interface com.example.android.application.ProtectedAgainstProguard { *; }
-keep public class * implements com.example.android.application.ProtectedAgainstProguard { *; }
-keep class * implements com.example.android.application.ProtectedAgainstProguard { *; }
-keep public class * extends com.example.android.application.ProtectedAgainstProguard { *; }
-keep class * extends com.example.android.application.ProtectedAgainstProguard { *; }


问:
How to Alter all specific datatype to another datatype in whole table
I have one table table_name with 50 decimal(18, 0) columns and I want to change it's datatype to decimal(18, 6)

I am trying

```<code>ALTER TABLE [table_name] ALTER COLUMN [column_name] [data_type]
</code>```

But for this, I have to queries 50 times.

How I do it in a single Query

答:
You have to add all colunm seprated by comma i.e.

ALTER TABLE [table_name] ALTER COLUMN [column_name1] [data_type],[column_name2] [data_type],so on;

Body:
I have one table table_name with 50 decimal(18, 0) columns and I want to change it's datatype to decimal(18, 6)

I am trying

ALTER TABLE [table_name] ALTER COLUMN [column_name] [data_type]

But for this, I have to queries 50 times.

How I do it in a single Query


问:
Spring boot + Hibernate + SqlAzure pagination issue
I have a java spring boot application that use hibernate as ORM. The database is an Azure SQL Server.

I've enabled the setShowSql  on vendor adapter configuration.

When I want to find objects, I used the TypedQuery's methods setFirstResult and setMaxResults and than invoke the getResultList method.

The query printed in the console doesn't contains the OFFSET and ROW FETCH clauses and it seems that Hibernate first retrieve all result and than apply the pagination on the resulted list.

This obviously causes performance issues.

Where am I doing wrong?

Below I report the sample code I used.

```<code>query.setFirstResult(pageable.getOffset());
query.setMaxResults(pageable.getPageSize());
...
query.getResultList()
</code>```

答:
The only time Hibernate will explicitly include the OFFSET and FETCH clauses under a SQL Server dialect will be when the following conditions are met:

You must use org.hibernate.dialect.SQLServer2012Dialect or any future 2012+ version.

Your query must include an ORDER BY clause.

Your query is not executing a TOP clause query.

The SQLServer2012Dialect uses a customized LimitHandler implementation called SQLServer2012LimitHandler that you can see here that explicitly handles this use case or otherwise falls back to the old behavior.

If both of the requirements above are being met but the logic is still fallig back to the old behavior for some reason, then it's a bug.  In that case, you probably should update HHH-12152 with a test case so we can fix it.

Body:
I have a java spring boot application that use hibernate as ORM. The database is an Azure SQL Server.

I've enabled the setShowSql  on vendor adapter configuration.

When I want to find objects, I used the TypedQuery's methods setFirstResult and setMaxResults and than invoke the getResultList method.

The query printed in the console doesn't contains the OFFSET and ROW FETCH clauses and it seems that Hibernate first retrieve all result and than apply the pagination on the resulted list.

This obviously causes performance issues.

Where am I doing wrong?

Below I report the sample code I used.

query.setFirstResult(pageable.getOffset());
query.setMaxResults(pageable.getPageSize());
...
query.getResultList()


问:
Closing a RandomAccessFile sometimes takes exactly 45 seconds
In my program, closing a java.util.RandomAccessFile sometimes takes exactly 45 seconds (well, almost exactly: between 44.998 and 45.003 seconds). The program creates and closes lots of small files. Usually closing the file is very quick (between 0 and 0.1 seconds). If I debug the program, it's stuck in the native method RandomAccessFile.close0.

The same problem also occurs when using FileOutputStream instead of RandomAccessFile (in which case the program is blocked in the native method FileOutputStream.close0).

Has somebody an idea what that could be? Can you reproduce the problem on your system (I can reproduce it only on a Mac, not on Windows XP; I didn't test yet on Linux)?

Update 2:

This only seems to happend on Mac OS X. I use JDK 1.6.0_22-b04. It happens on both 32-bit and 64-bit. On Windows XP it doesn't seem to occur.

My test case is:

```<code>import java.io.File;
import java.io.RandomAccessFile;
public class TestFileClose {
    public static void main(String... args) throws Exception {
        for (int i = 0; i < 100000; i++) {
            String name = "test" + i;
            RandomAccessFile r = new RandomAccessFile(name, "rw");
            r.write(0);
            long t = System.currentTimeMillis();
            r.close();
            long close = System.currentTimeMillis() - t;
            if (close > 200) {
                System.out.println("closing " + name +
                        " took " + close + " ms!");
            }
            if (i % 2000 == 0) {
                System.out.println("test " + i + "/100000");
            }
            new File(name).delete();
        }
    }
}
</code>```

Example output on my machine:

```<code>test 0/100000
test 2000/100000
test 4000/100000
test 6000/100000
test 8000/100000
test 10000/100000
closing test10030 took 44998 ms!
test 12000/100000
test 14000/100000
test 16000/100000
closing test16930 took 44998 ms!
test 18000/100000
test 20000/100000
</code>```

答:
It could be garbage collection activity, triggered by opening/closing a large number of RandomAccessFile objects; there may be nothing magic about 45 seconds - it could just be the time it takes the JVM on your machine to traverse the heap scavenging for objects to free. Having said that, 45 seconds is an awfully long GC pause; One application I worked on recently always suffered full GC's of about 11 seconds.

Try monitoring your program using JConsole or JVisualVM, or when you start the program try adding the following options:

```<code>-verbose:gc -Xloggc:gc.log -XX:+PrintGCDetails -XX:+PrintGCTimeStamps
</code>```

Then have a look in the gc.log file produced to see what the application stop times are; if you instrument your code to print timestamps you may be able to tie the close() behaviour to specific GC activity:

```<code>...
if (close > 200) {
    System.out.println(new Date());
    System.out.println("closing " + name +
                    " took " + close + " ms!");
}
...
</code>```

If it is GC related, in the gc.log file, you'd be looking for Full garbage collections and/or application stop times at around the timestamps your program outputs files.

Tinkering with the heap settings (-Xmx=... and XX:MaxPermSize=...) may then give you a completely different profile.

On a side note, if it is a temporary file, try using File file = File.createTempFile(prefix, suffix) and pass that into the RandomAccessFile - this may create files in /var/tmp (or whatever its called) on OS X, thus using an in-memory file system instead of a disk-based file system.

ContentLicense: CC BY-SA 2.5

Body:
In my program, closing a java.util.RandomAccessFile sometimes takes exactly 45 seconds (well, almost exactly: between 44.998 and 45.003 seconds). The program creates and closes lots of small files. Usually closing the file is very quick (between 0 and 0.1 seconds). If I debug the program, it's stuck in the native method RandomAccessFile.close0.

The same problem also occurs when using FileOutputStream instead of RandomAccessFile (in which case the program is blocked in the native method FileOutputStream.close0).

Has somebody an idea what that could be? Can you reproduce the problem on your system (I can reproduce it only on a Mac, not on Windows XP; I didn't test yet on Linux)?

Update 2:

This only seems to happend on Mac OS X. I use JDK 1.6.0_22-b04. It happens on both 32-bit and 64-bit. On Windows XP it doesn't seem to occur.

My test case is:

import java.io.File;
import java.io.RandomAccessFile;
public class TestFileClose {
    public static void main(String... args) throws Exception {
        for (int i = 0; i < 100000; i++) {
            String name = "test" + i;
            RandomAccessFile r = new RandomAccessFile(name, "rw");
            r.write(0);
            long t = System.currentTimeMillis();
            r.close();
            long close = System.currentTimeMillis() - t;
            if (close > 200) {
                System.out.println("closing " + name +
                        " took " + close + " ms!");
            }
            if (i % 2000 == 0) {
                System.out.println("test " + i + "/100000");
            }
            new File(name).delete();
        }
    }
}

Example output on my machine:

test 0/100000
test 2000/100000
test 4000/100000
test 6000/100000
test 8000/100000
test 10000/100000
closing test10030 took 44998 ms!
test 12000/100000
test 14000/100000
test 16000/100000
closing test16930 took 44998 ms!
test 18000/100000
test 20000/100000

Body:
It could be garbage collection activity, triggered by opening/closing a large number of RandomAccessFile objects; there may be nothing magic about 45 seconds - it could just be the time it takes the JVM on your machine to traverse the heap scavenging for objects to free. Having said that, 45 seconds is an awfully long GC pause; One application I worked on recently always suffered full GC's of about 11 seconds.

Try monitoring your program using JConsole or JVisualVM, or when you start the program try adding the following options:

-verbose:gc -Xloggc:gc.log -XX:+PrintGCDetails -XX:+PrintGCTimeStamps

Then have a look in the gc.log file produced to see what the application stop times are; if you instrument your code to print timestamps you may be able to tie the close() behaviour to specific GC activity:

...
if (close > 200) {
    System.out.println(new Date());
    System.out.println("closing " + name +
                    " took " + close + " ms!");
}
...

If it is GC related, in the gc.log file, you'd be looking for Full garbage collections and/or application stop times at around the timestamps your program outputs files.

Tinkering with the heap settings (-Xmx=... and XX:MaxPermSize=...) may then give you a completely different profile.

On a side note, if it is a temporary file, try using File file = File.createTempFile(prefix, suffix) and pass that into the RandomAccessFile - this may create files in /var/tmp (or whatever its called) on OS X, thus using an in-memory file system instead of a disk-based file system.


问:
how to add number with array join() method in python3?
Question About Join method in python,

I have data

```<code>data = ['my', 'name', 'is']
</code>```

I print like that

```<code>str1 = '\n'.join(str(e) for e in data)
print(str1)
</code>```

output

```<code>my
name
is
</code>```

how to add number like?

```<code>1 my
2 name
3 is
</code>```

答:
You can use enumerate:

```<code>print('\n'.join(str(i) + ' ' + j for i, j in enumerate(data, 1)))

1 my
2 name
3 is
</code>```

Body:
Question About Join method in python,

I have data

data = ['my', 'name', 'is']

I print like that

str1 = '\n'.join(str(e) for e in data)
print(str1)

output

my
name
is

how to add number like?

1 my
2 name
3 is

Body:
You can use enumerate:

print('\n'.join(str(i) + ' ' + j for i, j in enumerate(data, 1)))

1 my
2 name
3 is


问:
HTTP caching in API based application
Should we use http caching only for static stuff?

Or also in API responses could be using caching headers if data from API is not static? it can be changed by application's users.

答:
Caching is needed to gain performance but at the same time it increases the likelihood of the data being outdated. It's true for static resources as well. So if your app is under high load and you want to increase the speed - you may sacrifice up-to-date data for gain in performance.

Note, though, that client side needs to respect caching headers. We often work with browsers - they have it all figured out, but if our client is another service, then you need to ensure that it doesn't ignore the headers. This won't be for free - code will need to be written for this to happen.

Your cache may also be public or private. If it's public (any client is allowed to see the content), you may configure a reverse proxy (like nginx) between your server and the clients. Nginx can be set up to cache results (it also understands cache headers). So it may take off some load from your application by not letting requests through and instead returning cached copies.

Title: HTTP caching in API based application


问:
Fragments Overlapping views
I am working on fragments, but there is a problem when i switch from one fragment to other view overlap eachother.

I am using following code to switch fragments.

```<code>getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.mainContainer, new SecondsFragment())
            .addToBackStack(null)
            .commit();
</code>```

I know that using add() will only add newer fragment over the previous one. I dont want to use replace because it reloads everything when i return to that fragment using onBackPress() e-g i have REST API calls in first fragment when i open second fragment using replace() function and return to first fragment it will again call that REST API, which is not good for UX.

If i use add() to load second fragment, the view of second fragment overlaps view of first fragment, and returning to first fragment not call that REST API (my desired behaviour).

I also know that by setting background of fragments xml parent view, this issue can be resolved but then it will also cause accidental clicks on first fragments views again bad for UX, i also read in SO by setting parent view clickable to true will resolve this issue too, but as other developers said it is just a hack not a proper solution.

I am expecting users like commonsware to address this question.

Any suggestions/comments are highly welcome.

Thanks in Advance.

答:
I'll try to take a shot at that, I think you are miss-understanding the semantics of the add() in a FragmentTransaction, is that you are adding another fragment, this should not have any effect on fragment that are already added. Which means that both your fragments are active or RESUMED in terms of FragmentManager states.

The fact that your second fragment is as big as your first one, and is positioned on top of it, is merely an implementation detail only you are concerned with, as far as FragmentManager goes, both your fragments are RESUMED, active and intractable by the user.

Basically, if add() should somehow suspend the currently added fragment before adding the new one, why would we need another API for replace()

You are fixing one issue (not wanting to re-do a network request) by abusing a different feature (adding fragments).

If you want for only one fragment to be active at a time, then you need to remove the old fragment first, either by explicitly calling remove() or by having it done for you with a call to replace().

And to avoid the issue of doing a network request again, you can either:

Add your first fragment to the back stack add, and using pop() to go back to the same instance of your fragment, this will require some logic in your fragment to check if a certain state is not null, then no need to do the network call.

Saving the instance of your fragment manually in the containing Fragment/Activity, and then when you are adding your old fragment again, you add the existing instance, instead of creating a brand new one.

However, if your intent is indeed to have both of them added, but you want to restrict the user's ability to see/interact with the first fragment, you an use show(), hide() to do that.

Title: Fragments Overlapping views

Body:
I am working on fragments, but there is a problem when i switch from one fragment to other view overlap eachother.

I am using following code to switch fragments.

getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.mainContainer, new SecondsFragment())
            .addToBackStack(null)
            .commit();

I know that using add() will only add newer fragment over the previous one. I dont want to use replace because it reloads everything when i return to that fragment using onBackPress() e-g i have REST API calls in first fragment when i open second fragment using replace() function and return to first fragment it will again call that REST API, which is not good for UX.

If i use add() to load second fragment, the view of second fragment overlaps view of first fragment, and returning to first fragment not call that REST API (my desired behaviour).

I also know that by setting background of fragments xml parent view, this issue can be resolved but then it will also cause accidental clicks on first fragments views again bad for UX, i also read in SO by setting parent view clickable to true will resolve this issue too, but as other developers said it is just a hack not a proper solution.

I am expecting users like commonsware to address this question.

Any suggestions/comments are highly welcome.

Thanks in Advance.


问:
JavaScript form error state does not stay on same page
I'm doing a simple validation for a form. The JavaScript validation works fine and the pop up alert box appears with the correct errors, BUT, upon clicking "Ok", I get re-directed to the next page. Ideally, it is supposed to stay at the same page so that the user can amend his/her mistakes.

This is a school project.

```<code><script type = "text/javascript">

function show_alert() {
    if (document.getElementById('time1').value == document.getElementById('time2').value) alert("ERROR! You cannot book the same timing twice!")
    else if (document.getElementById('time1').value == document.getElementById('time3').value) alert("ERROR! You cannot book the same timing twice!")
    else if (document.getElementById('time1').value == document.getElementById('time4').value) alert("ERROR! You cannot book the same timing twice!")
    else if (document.getElementById('time1').value == "0") alert("ERROR! You cannot leave the first time slot blank!")
    else {}
}
</script>
</code>```

答:
This should be easy to fix.  In the onsubmit method of your form tag, do this:

```<code><form onsumbit="return show_alert();">
</code>```

Instead of

```<code> <form onsumbit="show_alert();">
</code>```

Without the return part, the script will run, and the form will be submitted anyhow.  Also, if there is an error condition in the script, you need to add a return false; otherwise the form will still be submitted, and return true; if there is no error.  You can edit the script like so:

```<code><script type = "text/javascript">

function show_alert() {
    if (document.getElementById('time1').value == document.getElementById('time2').value) {
        alert("ERROR! You cannot book the same timing twice!");
        return false;
    } else if (document.getElementById('time1').value == document.getElementById('time3').value) {
        alert("ERROR! You cannot book the same timing twice!");
        return false;
    } else if (document.getElementById('time1').value == document.getElementById('time4').value) {
        alert("ERROR! You cannot book the same timing twice!");
        return false;
    } else if (document.getElementById('time1').value == "0") {
        alert("ERROR! You cannot leave the first time slot blank!");
        return false;
    } else {
        return true;
    }
}

</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This should be easy to fix.  In the onsubmit method of your form tag, do this:

<form onsumbit="return show_alert();">

Instead of

 <form onsumbit="show_alert();">

Without the return part, the script will run, and the form will be submitted anyhow.  Also, if there is an error condition in the script, you need to add a return false; otherwise the form will still be submitted, and return true; if there is no error.  You can edit the script like so:

<script type = "text/javascript">

function show_alert() {
    if (document.getElementById('time1').value == document.getElementById('time2').value) {
        alert("ERROR! You cannot book the same timing twice!");
        return false;
    } else if (document.getElementById('time1').value == document.getElementById('time3').value) {
        alert("ERROR! You cannot book the same timing twice!");
        return false;
    } else if (document.getElementById('time1').value == document.getElementById('time4').value) {
        alert("ERROR! You cannot book the same timing twice!");
        return false;
    } else if (document.getElementById('time1').value == "0") {
        alert("ERROR! You cannot leave the first time slot blank!");
        return false;
    } else {
        return true;
    }
}

</script>


问:
How to customize reports in Odoo 11 in Qweb? How to send data from other model to the qweb report?
Does someone know a way to change the source of docs in a custom report? I need to load dataset from a view inherited from my model. Columns are the same than the model, it's just a data filter. </p>

答:
Odoo 11

There is no need to use odoo.report library anymore. It is deprecated. You can use odoo.tools insted of that:

from odoo.tools import report
```

<p>As it is explained here</p>

<p>And you can send data as Muhsin k says in his answer</p>

```self.env.ref('your_report_name').report_action(self, data=data)
```

<h2>Previous Odoo versions</h2>

<p>You have all the documentation here. Anyway if you wan to customize the data that you can use in a report you can use a method like this:</p>

<pre class="lang-py prettyprint-override"><code>from odoo import api, models

class ParticularReport(models.AbstractModel):
    _name = 'report.module.report_name'
    @api.model
    def render_html(self, docids, data=None):
        report_obj = self.env['report']
        report = report_obj._get_report_from_name('module.report_name')

        custom_data = self.env['model.name'].get_data()

        docargs = {
            'doc_ids': docids,
            'doc_model': report.model,
            'docs': self,
            'custom_data': custom_data,
        }
        return report_obj.render('module.report_name', docargs)
</code>```

The model model.name is the model where you want to get the information

Inherit Qweb Templates

The tag template is a shortcut for some views. The inherit_id attribute can be used here as well. Most of report are build with this kind of view:

<template id='report_invoice_document' inherit_id='account.report_invoice_document'>
    <xpath expr="//p[@t-if='o.payment_term.note']" position="after">

    </xpath>
</template>
```

Body:
Odoo 11

There is no need to use odoo.report library anymore. It is deprecated. You can use odoo.tools insted of that:

from odoo.tools import report

As it is explained here

And you can send data as Muhsin k says in his answer

self.env.ref('your_report_name').report_action(self, data=data)

Previous Odoo versions

You have all the documentation here. Anyway if you wan to customize the data that you can use in a report you can use a method like this:

from odoo import api, models

class ParticularReport(models.AbstractModel):
    _name = 'report.module.report_name'
    @api.model
    def render_html(self, docids, data=None):
        report_obj = self.env['report']
        report = report_obj._get_report_from_name('module.report_name')

        custom_data = self.env['model.name'].get_data()

        docargs = {
            'doc_ids': docids,
            'doc_model': report.model,
            'docs': self,
            'custom_data': custom_data,
        }
        return report_obj.render('module.report_name', docargs)

The model model.name is the model where you want to get the information

Inherit Qweb Templates

The tag template is a shortcut for some views. The inherit_id attribute can be used here as well. Most of report are build with this kind of view:

<template id='report_invoice_document' inherit_id='account.report_invoice_document'>
    <xpath expr="//p[@t-if='o.payment_term.note']" position="after">

        <!-- You can use you data object here -->

    </xpath>
</template>


问:
How to clear some fields in form - Redux-Form
I'm working on a page which has many input validations and logical bindings on it and every sprint iteration the page size increasing. So that, I have to find a beautiful and scalable solution.

Imagine, when user select a value from dropdown as 'A', some fields must be disabled, some fields must be cleared and some fields initilized with default values. I can change one related field (doesn't have validation rule like regexp or lenght constrait) value with some little code like

```<code>  this.props.dispatch(change('xForm','xField','xValue' ))
</code>```

My problem is that when I need to clear multiple fields,

It always blocked by my validation method and clear operation is failed ( Note : I supposed to be like that but not like that)

.

I tried some strategies as below but y,z,w fields have some text and it triggered validation rule and hanled errors. So that, inputs have  still old values, not cleared ones.

```<code>    //Clear
    this.props.dispatch(change('xForm','yField','' ))
    this.props.dispatch(change('xForm','zField','' ))
    this.props.dispatch(change('xForm','wField','' ))
</code>```

What are the best practises for clear inputs or assign some values to inputs in redux-form for pages which have highly dependent inputs.

I have been researching for 2 days but I couldn't find any optimal solution. (redux normalizer, redux form utils etc.)

Thanks.

答:
Try to use the dispatch function in meta object with following payload:

```<code>meta.dispatch({
  type: '@@redux-form/CHANGE',
  payload: null,
  meta: { ...meta, field: name },
})
</code>```

That should do the trick for any field you want.

Body:
I'm working on a page which has many input validations and logical bindings on it and every sprint iteration the page size increasing. So that, I have to find a beautiful and scalable solution.

Imagine, when user select a value from dropdown as 'A', some fields must be disabled, some fields must be cleared and some fields initilized with default values. I can change one related field (doesn't have validation rule like regexp or lenght constrait) value with some little code like

  this.props.dispatch(change('xForm','xField','xValue' ))

My problem is that when I need to clear multiple fields,

It always blocked by my validation method and clear operation is failed ( Note : I supposed to be like that but not like that)

.

I tried some strategies as below but y,z,w fields have some text and it triggered validation rule and hanled errors. So that, inputs have  still old values, not cleared ones.

    //Clear
    this.props.dispatch(change('xForm','yField','' ))
    this.props.dispatch(change('xForm','zField','' ))
    this.props.dispatch(change('xForm','wField','' ))

What are the best practises for clear inputs or assign some values to inputs in redux-form for pages which have highly dependent inputs.

I have been researching for 2 days but I couldn't find any optimal solution. (redux normalizer, redux form utils etc.)

Thanks.

Body:
Try to use the dispatch function in meta object with following payload:

meta.dispatch({
  type: '@@redux-form/CHANGE',
  payload: null,
  meta: { ...meta, field: name },
})

That should do the trick for any field you want.


问:
How to block the pop-up windows in chrome by Selenium
I am using the java and selenium to write the test script for automation. On here the target automated Org has some reminder pop-up windows so it makes the confusion of taking in the command of driver.getWindowHandles() command on my results.

I try the below code to try to Block the pop-up windows on the chrome

```<code>    System.setProperty("webdriver.chrome.driver", "//chrome path in system//");
    ChromeOptions options  = new ChromeOptions();
    options.setExperimentalOption("excludeSwitches", "disable-popup-blocking");
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    driver = new ChromeDriver(capabilities);
</code>```

But it's not working it's given the below error and prevent the chrome to launch:

from unknown error: cannot parse excludeSwitches

  from unknown error: must be a list

So what I should do for close those pop-up windows. Any answer is appreciated. I am using the chrome version:  '2.29.461591' and java.version: '1.8.0_92'

答:
You can try below code it is working fine for me:</p>

```<code>    System.setProperty("webdriver.chrome.driver", "//chrome path in system//");
    ChromeOptions options  = new ChromeOptions();
    //options.addArguments("incognito");
    options.addArguments("--disable-popup-blocking");
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    driver = new ChromeDriver(capabilities);
</code>```

Body:
I am using the java and selenium to write the test script for automation. On here the target automated Org has some reminder pop-up windows so it makes the confusion of taking in the command of driver.getWindowHandles() command on my results.

I try the below code to try to Block the pop-up windows on the chrome

    System.setProperty("webdriver.chrome.driver", "//chrome path in system//");
    ChromeOptions options  = new ChromeOptions();
    options.setExperimentalOption("excludeSwitches", "disable-popup-blocking");
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    driver = new ChromeDriver(capabilities);

But it's not working it's given the below error and prevent the chrome to launch:

from unknown error: cannot parse excludeSwitches

  from unknown error: must be a list

So what I should do for close those pop-up windows. Any answer is appreciated. I am using the chrome version:  '2.29.461591' and java.version: '1.8.0_92'

Body:
You can try below code it is working fine for me:

    System.setProperty("webdriver.chrome.driver", "//chrome path in system//");
    ChromeOptions options  = new ChromeOptions();
    //options.addArguments("incognito");
    options.addArguments("--disable-popup-blocking");
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    driver = new ChromeDriver(capabilities);


问:
XML deserialize to object
Hi,
I would like to deserialize (not so common) XML to object. Normal XML should looks like:

```<code><library>
<books>
 <book name="1"><author></author><details></details></book>
 <book name="2"><author></author><details></details></book>
 <book name="2"><author></author><details></details></book>
</books>
</library>
</code>```

As you can see there is 'books' branch inside which I have some 'book' elements. It is ok, easy to deserialize etc. However my XML looks different. Inside 'books' there are elements with random names. Instead of 'book' element there is element with book name itself (as element name). What is more inside these elements there are always the same elements like 'author' and 'details'.

Please have a look at this:

```<code><library>
<books>
 <1><author></author><details></details></1>
 <2><author></author><details></details></2>
 <3><author></author><details></details></3>
</books>
</library>
</code>```

Any suggestion how to create objects from the  second XML?

答:
Using xml linq.  I change xml so tagsw 1,2,3 are a,b,c since tags can't start with a number</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication16
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Book.books = doc.Descendants("books").FirstOrDefault().Elements().Select(x => new Book() {
                name = x.Name.LocalName,
                author = (string)x.Element("author"),
                detail = (string)x.Element("details")
            }).ToList();
        }
    }

    public class Book
    {
        public static List<Book> books = new List<Book>();

        public string name { get; set;}
        public string author { get; set;}
        public string detail { get; set;}
    }

}
</code>```

Title: XML deserialize to object

Body:
Hi,
I would like to deserialize (not so common) XML to object. Normal XML should looks like:

<library>
<books>
 <book name="1"><author></author></book>
 <book name="2"><author></author></book>
 <book name="2"><author></author></book>
</books>
</library>

As you can see there is 'books' branch inside which I have some 'book' elements. It is ok, easy to deserialize etc. However my XML looks different. Inside 'books' there are elements with random names. Instead of 'book' element there is element with book name itself (as element name). What is more inside these elements there are always the same elements like 'author' and 'details'.

Please have a look at this:

<library>
<books>
 <1><author></author></1>
 <2><author></author></2>
 <3><author></author></3>
</books>
</library>

Any suggestion how to create objects from the  second XML?

Body:
Using xml linq.  I change xml so tagsw 1,2,3 are a,b,c since tags can't start with a number

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication16
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Book.books = doc.Descendants("books").FirstOrDefault().Elements().Select(x => new Book() {
                name = x.Name.LocalName,
                author = (string)x.Element("author"),
                detail = (string)x.Element("details")
            }).ToList();
        }
    }

    public class Book
    {
        public static List<Book> books = new List<Book>();

        public string name { get; set;}
        public string author { get; set;}
        public string detail { get; set;}
    }

}


问:
JSON request to GET HOST list by GroupName
I have Zabbix 3.2.

I want to get HOST List via API by search Group

I found and checked variant by GroupID
For example:

```<code>zabbix_get= \
        {
            "jsonrpc": "2.0",
            "method": "host.get",
            "params": {
                "output": ["host"],
                "groupids": ["1945"],
            },
            "auth": authToken.get("result"),
            "id": authToken.get("id")
        }
</code>```

Is it possible to search by group name, for example name "Group1"?

答: While you cannot filter for group membership in host.get, you could use hostgroup.get with the selectHosts parameter.

Body:
I have Zabbix 3.2.

I want to get HOST List via API by search Group

I found and checked variant by GroupID
For example:

zabbix_get= \
        {
            "jsonrpc": "2.0",
            "method": "host.get",
            "params": {
                "output": ["host"],
                "groupids": ["1945"],
            },
            "auth": authToken.get("result"),
            "id": authToken.get("id")
        }

Is it possible to search by group name, for example name "Group1"?


问:
What is the class that declaring method of another class
I remember on my previous web development job that they have something like this:

sampleClassBean.java:

```<code>public class sampleClassBean
{
    public String doSomeStrings(String a, String b){}

    public Int doSomeInt(Integer i, integer j){}

    public Boolean doSomeBoolean(Boolean result){}
}
</code>```

and then there's sampleClassBeanImpl

```<code>public class sampleClassBeanImpl
{
  public String doSomeStrings(String a, String b)
  {
     //do some process
     return "";
  }

public Integer doSomeInt(Integer i, Integer j)
  {
     //do some process
     return 0;
  }

public Boolean doSomeBoolean(Boolean result)
  {
     //do some process
     return false;
  }
}
</code>```

For what I understand is that, there's 2 class, 1st class that declare methods, now 2nd class's methods will depend on what is declared on the 1st class. If the 2nd class create a method that is not declared in 1st class there will be an error. Hope you understand what i'm saying.

What I need to know is what exactly that? What do you call that process? How to do that? What are the benefits of doing that? Is it a good programming practice?

答:
Yes it is good practice, you are talking about interfaces:

Java includes a concept called interfaces. A Java interface is a bit like a class, except a Java interface can only contain method signatures and fields. An Java interface cannot contain an implementation of the methods, only the signature (name, parameters and exceptions) of the method.

The interface:

```<code>public interface SampleClassBean {
    public String doSomeStrings(String a, String b);
    public int doSomeInt(int i, int j);
    public Boolean doSomeBoolean(Boolean result);
}
</code>```

And the implementation:

```<code>public class SampleClassBeanImpl implements SampleClassBean {
    @Override
    public String doSomeStrings(String a, String b) {
        return null;
    }

    @Override
    public int doSomeInt(int i, int j) {
        return 0;
    }

    @Override
    public Boolean doSomeBoolean(Boolean result) {
        return null;
    }
}
</code>```

Interfaces are really useful because unlike other languages Java doesn't support multiple inheritance but you can implement all the interfaces you wish!

Have a read of this it'll help you understand interfaces and when to implement them.

Body:
I remember on my previous web development job that they have something like this:

sampleClassBean.java:

public class sampleClassBean
{
    public String doSomeStrings(String a, String b){}

    public Int doSomeInt(Integer i, integer j){}

    public Boolean doSomeBoolean(Boolean result){}
}

and then there's sampleClassBeanImpl

public class sampleClassBeanImpl
{
  public String doSomeStrings(String a, String b)
  {
     //do some process
     return "";
  }

public Integer doSomeInt(Integer i, Integer j)
  {
     //do some process
     return 0;
  }

public Boolean doSomeBoolean(Boolean result)
  {
     //do some process
     return false;
  }
}

For what I understand is that, there's 2 class, 1st class that declare methods, now 2nd class's methods will depend on what is declared on the 1st class. If the 2nd class create a method that is not declared in 1st class there will be an error. Hope you understand what i'm saying.

What I need to know is what exactly that? What do you call that process? How to do that? What are the benefits of doing that? Is it a good programming practice?

Body:
Yes it is good practice, you are talking about interfaces:

Java includes a concept called interfaces. A Java interface is a bit like a class, except a Java interface can only contain method signatures and fields. An Java interface cannot contain an implementation of the methods, only the signature (name, parameters and exceptions) of the method.

The interface:

public interface SampleClassBean {
    public String doSomeStrings(String a, String b);
    public int doSomeInt(int i, int j);
    public Boolean doSomeBoolean(Boolean result);
}

And the implementation:

public class SampleClassBeanImpl implements SampleClassBean {
    @Override
    public String doSomeStrings(String a, String b) {
        return null;
    }

    @Override
    public int doSomeInt(int i, int j) {
        return 0;
    }

    @Override
    public Boolean doSomeBoolean(Boolean result) {
        return null;
    }
}

Interfaces are really useful because unlike other languages Java doesn't support multiple inheritance but you can implement all the interfaces you wish!

Have a read of this it'll help you understand interfaces and when to implement them.


问:
Problem wrapping Extjs Accordion

I am tring to start and build an accordion menu.

I want to use it as an xtype or new MyVar(). but i get few JS Errors

this is my code:

```<code>var AccordionMenu = Ext.extend(Ext.Panel, {
    layout: 'accordion',
    id:'action-panel',
        region:'west',
        split:true,
        collapsible: true,
        collapseMode: 'mini',
        width:200,
        minWidth: 150,
        border: false,
        baseCls:'x-plain',

    items: [{
        title: 'Affiliates',
        html: 'Empty',
        cls: 'empty'
    },{
        title: 'Brands',
        html: 'Empty',
        cls: 'empty'
    }]
});

Ext.reg('accordion_menu', AccordionMenu);

Ext.onReady(function() {
    Ext.QuickTips.init();

            var viewport = new Ext.Viewport({
                layout:'border',
                items:[
                    new AccordionMenu()
                   ,
                   {
                    region:'center',
                    margins:'5 5 5 0',
                    cls:'empty',
                    bodyStyle:'background:#f1f1f1',
                    html:'test'
                }]
            });

});
</code>```

this is the errors:

```<code>    this.items.add is not a function

Line 12777
</code>```

Thanks

答:
Sample code:

```<code>var AccordionMenu = Ext.extend(Ext.Panel, {
    constructor: function(cfg) {
        var config = {
            layout: 'accordion',
            region: 'west',
            split: true,
            width: 200,
            layout: 'accordion',
            animate: true,
            fill: true,
            items: [{
                title: 'Affiliates',
                html: 'Empty',
                cls: 'empty'
            },{
                title: 'Brands',
                html: 'Empty',
                cls: 'empty'
            }]
        };
        Ext.apply(config, cfg);
        AccordionMenu.superclass.constructor.call(this, config);
    }
});

Ext.reg('accordion_menu', AccordionMenu);

Ext.onReady(function() {
    Ext.QuickTips.init();
    var viewport = new Ext.Viewport({
        layout:'border',
        items:[
            new AccordionMenu(),
        {
            region:'center',
            margins:'5 5 5 0',
            cls:'empty',
            bodyStyle:'background:#f1f1f1',
            html:'test'
        }]
    });
});
</code>```

Update

So sorry for didn't notice I have written the item configurations into the prototype of the Application object, which causes your this.items.add cannot be called because they are basically simple json configurations!

The code has been fixed, please take a look and have a try. Should work :)

Personal Suggestion

If you are not going to share this components (use it in many places), I would suggest you to just create a Panel with the required configurations. Although creating components by extending other components is a good practice, but it is a lot more complicated and sometimes can cause problem just like I did earlier.

The code below should work also:

```<code>Ext.onReady(function() {
    Ext.QuickTips.init();
    var viewport = new Ext.Viewport({
        layout:'border',
        items:[{
            layout: 'accordion',
            region: 'west',
            split: true,
            width: 200,
            layout: 'accordion',
            animate: true,
            fill: true,
            items: [{
                title: 'Affiliates',
                html: 'Empty',
                cls: 'empty'
            },{
                title: 'Brands',
                html: 'Empty',
                cls: 'empty'
            }]
        },{
            region:'center',
            margins:'5 5 5 0',
            cls:'empty',
            bodyStyle:'background:#f1f1f1',
            html:'test'
        }]
    });
});
</code>```

Although messy, but it's easy to understand, right?

Title: Problem wrapping Extjs Accordion

Body:
I am tring to start and build an accordion menu.

I want to use it as an xtype or new MyVar(). but i get few JS Errors

this is my code:

var AccordionMenu = Ext.extend(Ext.Panel, {
    layout: 'accordion',
    id:'action-panel',
        region:'west',
        split:true,
        collapsible: true,
        collapseMode: 'mini',
        width:200,
        minWidth: 150,
        border: false,
        baseCls:'x-plain',

    items: [{
        title: 'Affiliates',
        html: 'Empty',
        cls: 'empty'
    },{
        title: 'Brands',
        html: 'Empty',
        cls: 'empty'
    }]
});

Ext.reg('accordion_menu', AccordionMenu);

Ext.onReady(function() {
    Ext.QuickTips.init();

            var viewport = new Ext.Viewport({
                layout:'border',
                items:[
                    new AccordionMenu()
                   ,
                   {
                    region:'center',
                    margins:'5 5 5 0',
                    cls:'empty',
                    bodyStyle:'background:#f1f1f1',
                    html:'test'
                }]
            });

});

this is the errors:

    this.items.add is not a function

Line 12777

Thanks

Body:
Sample code:

var AccordionMenu = Ext.extend(Ext.Panel, {
    constructor: function(cfg) {
        var config = {
            layout: 'accordion',
            region: 'west',
            split: true,
            width: 200,
            layout: 'accordion',
            animate: true,
            fill: true,
            items: [{
                title: 'Affiliates',
                html: 'Empty',
                cls: 'empty'
            },{
                title: 'Brands',
                html: 'Empty',
                cls: 'empty'
            }]
        };
        Ext.apply(config, cfg);
        AccordionMenu.superclass.constructor.call(this, config);
    }
});

Ext.reg('accordion_menu', AccordionMenu);

Ext.onReady(function() {
    Ext.QuickTips.init();
    var viewport = new Ext.Viewport({
        layout:'border',
        items:[
            new AccordionMenu(),
        {
            region:'center',
            margins:'5 5 5 0',
            cls:'empty',
            bodyStyle:'background:#f1f1f1',
            html:'test'
        }]
    });
});

Update

So sorry for didn't notice I have written the item configurations into the prototype of the Application object, which causes your this.items.add cannot be called because they are basically simple json configurations!

The code has been fixed, please take a look and have a try. Should work :)

Personal Suggestion

If you are not going to share this components (use it in many places), I would suggest you to just create a Panel with the required configurations. Although creating components by extending other components is a good practice, but it is a lot more complicated and sometimes can cause problem just like I did earlier.

The code below should work also:

Ext.onReady(function() {
    Ext.QuickTips.init();
    var viewport = new Ext.Viewport({
        layout:'border',
        items:[{
            layout: 'accordion',
            region: 'west',
            split: true,
            width: 200,
            layout: 'accordion',
            animate: true,
            fill: true,
            items: [{
                title: 'Affiliates',
                html: 'Empty',
                cls: 'empty'
            },{
                title: 'Brands',
                html: 'Empty',
                cls: 'empty'
            }]
        },{
            region:'center',
            margins:'5 5 5 0',
            cls:'empty',
            bodyStyle:'background:#f1f1f1',
            html:'test'
        }]
    });
});

Although messy, but it's easy to understand, right?


问:
TagHelpers doesn't get invoked after moving them to a different project
I'm having some issues with asp.net core not finding and invoking my tag helpers. After I moved the taghelpers from a seperate assembly (LC.Tools.Utility.TagHelpers) to LC.Tools.Utility it doesnt seem like they get discovered even though the namespace is the same as before.

Sample cshtml:

```<code><lc:css src="styles.min.css" />
<lc:css src="styles.bootstrap.min.css" />
<lc:css src="styles._layout.min.css" />
</code>```

When looking at the source for the page the tags are exactly the same.

_ViewImports.cshtml:

```<code>@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, LC.Smokers.Albino.TagHelpers
@addTagHelper *, LC.Tools.Utility.TagHelpers
</code>```

LC.Tools.Utility.TagHelpers.IncludeCssTagHelper.cs (in assembly LC.Tools.Utility):

```<code>using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace LC.Tools.Utility.TagHelpers
{
    [HtmlTargetElement("lc:css", Attributes = "src", TagStructure = TagStructure.WithoutEndTag)]
    public class IncludeCssTagHelper : Base
    {
        public IncludeCssTagHelper(IHostingEnvironment env) : base(env) { }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "link";
            output.TagMode = TagMode.SelfClosing;

            bool isDebug = this.Environment.IsDevelopment() && this.DebugSrc.Length > 0;
            string path = "/CSS/";

            if (isDebug)
            {
                path += this.DebugSrc;

                if (Utility.IsUrl(this.DebugSrc))
                {
                    path = this.DebugSrc;
                }
            }
            else if (!string.IsNullOrEmpty(this.Src))
            {
                path += this.Src;

                if (Utility.IsUrl(this.Src))
                {
                    path = this.Src;
                }
            }

            output.Attributes.Clear();

            output.Attributes.SetAttribute("href", path.ToLower());
            output.Attributes.SetAttribute("rel", "stylesheet");
            output.Attributes.SetAttribute("type", "text/css");

            base.Process(context, output);
        }

        [HtmlAttributeName("src")]
        public string Src { get; set; }

        [HtmlAttributeName("debug-src")]
        public string DebugSrc { get; set; } = string.Empty;
    }
}
</code>```

I've tried deleting the bin and obj folders from all the projects and
  rebuild the entire solution and removed and added reference to the
  project.

Any ideas?

答:
The addTagHelper directive expects two comma-separated parameters. The docs has this to say about how it works:

The first parameter after @addTagHelper specifies the Tag Helpers to load (we are using "*" for all Tag Helpers), and the second parameter "Microsoft.AspNetCore.Mvc.TagHelpers" specifies the assembly containing the Tag Helpers.

Note what I've highlighted in bold: It's not the namespace that is needed; it's the assembly. In your example, you need to change that second parameter to reflect the new hosting assembly:

```<code>@addTagHelper *, LC.Tools.Utility
</code>```

Body:
I'm having some issues with asp.net core not finding and invoking my tag helpers. After I moved the taghelpers from a seperate assembly (LC.Tools.Utility.TagHelpers) to LC.Tools.Utility it doesnt seem like they get discovered even though the namespace is the same as before.

Sample cshtml:

<lc:css src="styles.min.css" />
<lc:css src="styles.bootstrap.min.css" />
<lc:css src="styles._layout.min.css" />

When looking at the source for the page the tags are exactly the same.

_ViewImports.cshtml:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, LC.Smokers.Albino.TagHelpers
@addTagHelper *, LC.Tools.Utility.TagHelpers

LC.Tools.Utility.TagHelpers.IncludeCssTagHelper.cs (in assembly LC.Tools.Utility):

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace LC.Tools.Utility.TagHelpers
{
    [HtmlTargetElement("lc:css", Attributes = "src", TagStructure = TagStructure.WithoutEndTag)]
    public class IncludeCssTagHelper : Base
    {
        public IncludeCssTagHelper(IHostingEnvironment env) : base(env) { }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "link";
            output.TagMode = TagMode.SelfClosing;

            bool isDebug = this.Environment.IsDevelopment() && this.DebugSrc.Length > 0;
            string path = "/CSS/";

            if (isDebug)
            {
                path += this.DebugSrc;

                if (Utility.IsUrl(this.DebugSrc))
                {
                    path = this.DebugSrc;
                }
            }
            else if (!string.IsNullOrEmpty(this.Src))
            {
                path += this.Src;

                if (Utility.IsUrl(this.Src))
                {
                    path = this.Src;
                }
            }

            output.Attributes.Clear();

            output.Attributes.SetAttribute("href", path.ToLower());
            output.Attributes.SetAttribute("rel", "stylesheet");
            output.Attributes.SetAttribute("type", "text/css");

            base.Process(context, output);
        }

        [HtmlAttributeName("src")]
        public string Src { get; set; }

        [HtmlAttributeName("debug-src")]
        public string DebugSrc { get; set; } = string.Empty;
    }
}

I've tried deleting the bin and obj folders from all the projects and
  rebuild the entire solution and removed and added reference to the
  project.

Any ideas?

Body:
The addTagHelper directive expects two comma-separated parameters. The docs has this to say about how it works:

The first parameter after @addTagHelper specifies the Tag Helpers to load (we are using "*" for all Tag Helpers), and the second parameter "Microsoft.AspNetCore.Mvc.TagHelpers" specifies the assembly containing the Tag Helpers.

Note what I've highlighted in bold: It's not the namespace that is needed; it's the assembly. In your example, you need to change that second parameter to reflect the new hosting assembly:

@addTagHelper *, LC.Tools.Utility


问:
Python multiprocessing on OpenCV images
I need to accelerate some image processing by means of multithreading on a multicore architecture.

My images are OpenCV objects.

I tried approaching the problem with the threading module, but it turns out not to perform true parallelism (!) because of the GIL issue. I have tried with the multiprocessing module, but it turns out that my objects are not shared between processes (!)

My processing needs to work on different sections of the same image simultaneously (so that the Queue paradigm is irrelevant).

What can I do ?

答:
I eventually found a solution here to share NumPy arrays when using the multiprocessing model: http://briansimulator.org/sharing-numpy-arrays-between-processes/

The main idea is to flatten the image bitmap as a linear buffer, copy it to a shared array, and map it back to a bitmap (without copy) in the receiving processes.

This is not fully satisfying as multithreading would be more resource-friendly than multiprocessing (it takes a huge amount of memory), but at least it works, with minimal effort.

Title: Python multiprocessing on OpenCV images


问:
Timeout does not log out if windows is locked
I have been recently working on the timeout function (used javascript - setInterval). I did test it, it worked exactly the way I want apart from one tiny detail. Whenever a logged in user sleeps the computer, the session is still active and timeout keeps counting the time. Consequently, after waking the PC up, let's say after 40 min, the timeout says e.g. -10 min and the user is still logged in. If he clicks anything or refresh the page, the service will refresh and the timeout is being restarted to the initial value like nothing happened (user is still logged in). Is there a way of making sure that the user is going to be logged out after waking the PC up?

Thanks a lot in advance!

答:
Rather than using setTimeout/setInterval for you logout directly, perhaps try something like this:

var targetTime = moment(new Date()).add(5 ,'s');
var intervalHolder = {};
console.log("go")
intervalHolder.interval = setInterval(() => {
  if (moment(new Date()).isAfter(targetTime)) {
    console.log('TimedOut');
    clearInterval(intervalHolder.interval);
  }
},1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://momentjs.com/downloads/moment.js"></script></code>```

Body:
Rather than using setTimeout/setInterval for you logout directly, perhaps try something like this:

var targetTime = moment(new Date()).add(5 ,'s');
var intervalHolder = {};
console.log("go")
intervalHolder.interval = setInterval(() => {
  if (moment(new Date()).isAfter(targetTime)) {
    console.log('TimedOut');
    clearInterval(intervalHolder.interval);
  }
},1000);

<script src="https://momentjs.com/downloads/moment.js"></script>


问:
Drawable with a four-color border With Circular Shape
Is it possible to achieve the following as a drawable (for a background) using a Layer-List ???

答:
For layer List use:

```<code> <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <size
                android:width="56dp"
                android:height="56dp" />

            <stroke
                android:width="10dp"
                android:dashGap="20dp"
                android:color="#0000ff" />
        </shape>
    </item>
    <item>
        <shape android:shape="oval">
            <size
                android:width="25dp"
                android:height="24dp" />

            <stroke
                android:width="10dp"
                android:color="#FF0000"
                android:dashGap="20dp"
                android:dashWidth="10dp" />
        </shape>
    </item>

</layer-list>
</code>```

Output:

Change your dash gap and stroke width accordingly..

Body:
For layer List use:

 <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <size
                android:width="56dp"
                android:height="56dp" />

            <stroke
                android:width="10dp"
                android:dashGap="20dp"
                android:color="#0000ff" />
        </shape>
    </item>
    <item>
        <shape android:shape="oval">
            <size
                android:width="25dp"
                android:height="24dp" />

            <stroke
                android:width="10dp"
                android:color="#FF0000"
                android:dashGap="20dp"
                android:dashWidth="10dp" />
        </shape>
    </item>

</layer-list>

Output:

Change your dash gap and stroke width accordingly..


问:
C++ - How can I avoid this header from appearing twice?
At: http://www.learncpp.com/cpp-tutorial/110-a-first-look-at-the-preprocessor/

Under Header guards, there are those code snippets:

add.h:

```<code>#include "mymath.h"
int add(int x, int y);
</code>```

subtract.h:

```<code>#include "mymath.h"
int subtract(int x, int y);
</code>```

main.cpp:

```<code>#include "add.h"
#include "subtract.h"
</code>```

How can I avoid #include "mymath.h" from appearing twice in main.cpp?

Thanks.

答:
The lines right below that example explain it.  Your mymath.h file should look like this:

```<code>#ifndef MYMATH_H
#define MYMATH_H

// your declarations here

#endif
</code>```

Every header file should follow this basic format.  This allows a header file to be included by any file that needs it (both header and source files), but the actual declarations will only be included at most once in each source file.

Body:
At: http://www.learncpp.com/cpp-tutorial/110-a-first-look-at-the-preprocessor/

Under Header guards, there are those code snippets:

add.h:

#include "mymath.h"
int add(int x, int y);

subtract.h:

#include "mymath.h"
int subtract(int x, int y);

main.cpp:

#include "add.h"
#include "subtract.h"

How can I avoid #include "mymath.h" from appearing twice in main.cpp?

Thanks.

Body:
The lines right below that example explain it.  Your mymath.h file should look like this:

#ifndef MYMATH_H
#define MYMATH_H

// your declarations here

#endif

Every header file should follow this basic format.  This allows a header file to be included by any file that needs it (both header and source files), but the actual declarations will only be included at most once in each source file.


问:
How can I set reactdate-picker dropdown view to upper
Normal style of drop down view is at bottom after click,HOw can I set to upper place.plz Let me fix that.
Here is my nomal datepicker in reactjs.</p>

```<code> <DatePicker
     selected={this.state.startDate}
    onChange={this.handleDateChange}
 />
</code>```

答:
Add prop for popperPlacement, like this:

```<code><DatePicker
  ...
  popperPlacement="top-start"
>
</code>```

React DatePicker does that automatically if there is not enough room for it on the bottom of the page, but this way you can "force" it.

See The source for additional placement options.

Body:
Normal style of drop down view is at bottom after click,HOw can I set to upper place.plz Let me fix that.
Here is my nomal datepicker in reactjs.

 <DatePicker
     selected={this.state.startDate}
    onChange={this.handleDateChange}
 />

Body:
Add prop for popperPlacement, like this:

<DatePicker
  ...
  popperPlacement="top-start"
>

React DatePicker does that automatically if there is not enough room for it on the bottom of the page, but this way you can "force" it.

See The source for additional placement options.


问:
Php JSON encode array and unexpected token error in decoding
I got an array from an SQL query, encoded it and when I decode in javascript I receive the error

Unexpected token a in JSON at position 0

The var_dump of the array before the encode:

```<code>array(1) { [0]=> array(10) { ["order_id"]=> string(10) "1512642144"
["order_erp_id"]=> string(1) "0" ["order_type"]=> string(3) "web"
["order_date"]=> string(23) "2017-12-07 11:22:24.263" ["order_total"]=>
string(4) "0.00" ["order_desc1"]=> string(3) "web" ["order_desc2"]=>
string(4) "test" ["no_items"]=> string(1) "0" ["order_count"]=> int(1)
["item_arr"]=> string(0) "" } }
[{"order_id":"1512642144","order_erp_id":"0","order_type":"web",
"order_date":"2017-12-07 11:22:24.263","order_total":"0.00",
"order_desc1":"web","order_desc2":"test","no_items":"0",
"order_count":1,"item_arr":""}]
</code>```

then I  encode and send it with:

```<code>echo json_encode($order_item_arr);
</code>```

On the client side, I receive the data and before the decoding step I have this from the console.log(data); in javascript:

```<code>array(1) {
[0]=>
array(10) {
["order_id"]=>
string(10) "1512642144"
["order_erp_id"]=>
string(1) "0"
["order_type"]=>
string(3) "web"
["order_date"]=>
string(23) "2017-12-07 11:22:24.263"
["order_total"]=>
string(4) "0.00"
["order_desc1"]=>
string(3) "web"
["order_desc2"]=>
string(4) "test"
["no_items"]=>
string(1) "0"
["order_count"]=>
int(1)
["item_arr"]=>
string(0) ""
  }
}

[{"order_id":"1512642144","order_erp_id":"0","order_type":"web",
"order_date":"2017-12-07 11:22:24.263","order_total":"0.00",
"order_desc1":"web","order_desc2":"test","no_items":"0",
"order_count":1,"item_arr":""}]
</code>```

So it looks like quite ok, and when I decode it with JSON.parse(data); I have the error:

```<code>VM414:1 Uncaught SyntaxError: Unexpected token a in JSON at position 0
</code>```

答:
JSON.parse() is used to convert a string containing JSON notation into a Javascript object.

Your code turns the object into a string (by calling .toString()) in order to try to parse it as JSON text.
The default .toString() returns "[object Object]", which is not valid JSON; hence the error

Body:
I got an array from an SQL query, encoded it and when I decode in javascript I receive the error

Unexpected token a in JSON at position 0

The var_dump of the array before the encode:

array(1) { [0]=> array(10) { ["order_id"]=> string(10) "1512642144"
["order_erp_id"]=> string(1) "0" ["order_type"]=> string(3) "web"
["order_date"]=> string(23) "2017-12-07 11:22:24.263" ["order_total"]=>
string(4) "0.00" ["order_desc1"]=> string(3) "web" ["order_desc2"]=>
string(4) "test" ["no_items"]=> string(1) "0" ["order_count"]=> int(1)
["item_arr"]=> string(0) "" } }
[{"order_id":"1512642144","order_erp_id":"0","order_type":"web",
"order_date":"2017-12-07 11:22:24.263","order_total":"0.00",
"order_desc1":"web","order_desc2":"test","no_items":"0",
"order_count":1,"item_arr":""}]

then I  encode and send it with:

echo json_encode($order_item_arr);

On the client side, I receive the data and before the decoding step I have this from the console.log(data); in javascript:

array(1) {
[0]=>
array(10) {
["order_id"]=>
string(10) "1512642144"
["order_erp_id"]=>
string(1) "0"
["order_type"]=>
string(3) "web"
["order_date"]=>
string(23) "2017-12-07 11:22:24.263"
["order_total"]=>
string(4) "0.00"
["order_desc1"]=>
string(3) "web"
["order_desc2"]=>
string(4) "test"
["no_items"]=>
string(1) "0"
["order_count"]=>
int(1)
["item_arr"]=>
string(0) ""
  }
}

[{"order_id":"1512642144","order_erp_id":"0","order_type":"web",
"order_date":"2017-12-07 11:22:24.263","order_total":"0.00",
"order_desc1":"web","order_desc2":"test","no_items":"0",
"order_count":1,"item_arr":""}]

So it looks like quite ok, and when I decode it with JSON.parse(data); I have the error:

VM414:1 Uncaught SyntaxError: Unexpected token a in JSON at position 0


问:
Spring Boot test mock bean
How mock 2 beans when one is into second ?

```<code>public class A {
...
}

public class B {
private A a;
}
</code>```

I tried:

```<code>@MockBean
private A a;

@InjectMocks
private B b;

@Before
public void executedBeforeEach() {
MockitoAnnotations.initMocks(this);
}
</code>```

but had exception:

```<code>org.mockito.exceptions.base.MockitoException:
Cannot instantiate @InjectMocks field named 'B'.
You haven't provided the instance at field declaration so I tried to     construct the instance.
However, I failed because: the type 'B' is an interface.
</code>```

spring version:

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
    <relativePath/>
</parent>
</code>```

test dependency:

```<code><dependencies>
...
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    </dependency>
 </dependencies>
</code>```

how to do it right  ?where did I make a mistake ?

答:
You just need to autowire B. By using the annotation @MockBean you are telling the test Spring context to replace the actual bean of type A with a mock and this will automatically be injected into everywhere A in included (i.e. in your B bean).

```<code>@MockBean
private A a;

@Autowire
private B b;
</code>```

This is under the assumption that you are annotating your test class with @SpringBootTest

Title: Spring Boot test mock bean

Body:
How mock 2 beans when one is into second ?

public class A {
...
}

public class B {
private A a;
}

I tried:

@MockBean
private A a;

@InjectMocks
private B b;

@Before
public void executedBeforeEach() {
MockitoAnnotations.initMocks(this);
}

but had exception:

org.mockito.exceptions.base.MockitoException:
Cannot instantiate @InjectMocks field named 'B'.
You haven't provided the instance at field declaration so I tried to     construct the instance.
However, I failed because: the type 'B' is an interface.

spring version:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
    <relativePath/>
</parent>

test dependency:

<dependencies>
...
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    </dependency>
 </dependencies>

how to do it right  ?where did I make a mistake ?

Body:
You just need to autowire B. By using the annotation @MockBean you are telling the test Spring context to replace the actual bean of type A with a mock and this will automatically be injected into everywhere A in included (i.e. in your B bean).

@MockBean
private A a;

@Autowire
private B b;

This is under the assumption that you are annotating your test class with @SpringBootTest


答: That's ok if they included twice if all the headers files have header guards.  The second and all subsequent inclusions would just add empty lines and there won't be any code duplication.  Just make sure that mymath.h has header guards as well.

Title: C++ - How can I avoid this header from appearing twice?


问:
Convert array to conditional php
I have and array, and I want to convert it into an if conditional.

```<code>$array = ['check 1', 'check 2', 'check 3'];
</code>```

I want the final result to work like this:

```<code>if ($var == 'check 1' || $var == 'check 2' || $var == 'check 3') {
    // Do here.
}
</code>```

I don't have any inspiration, I already searched for convert array to if condition but I couldn't find anything.

How can I convert the array into an if conditional?

答:
Instead of multiple || (OR) conditions use in_array()

```<code>if (in_array($var, $array)) {
    // do here
}
</code>```

Output:-https://eval.in/914346

If you want to check multiple variables against array then do like this:-

```<code>if (in_array($var, $array) || in_array($var1, $array)){
  //do here
}
</code>```

Output:- https://eval.in/914351

Note:- If you can clarify more about all your variables and what conditions you want for all those variables, you will get more accurate answer

Title: Convert array to conditional php

Body:
I have and array, and I want to convert it into an if conditional.

$array = ['check 1', 'check 2', 'check 3'];

I want the final result to work like this:

if ($var == 'check 1' || $var == 'check 2' || $var == 'check 3') {
    // Do here.
}

I don't have any inspiration, I already searched for convert array to if condition but I couldn't find anything.

How can I convert the array into an if conditional?

Body:
Instead of multiple || (OR) conditions use in_array()

if (in_array($var, $array)) {
    // do here
}

Output:-https://eval.in/914346

If you want to check multiple variables against array then do like this:-

if (in_array($var, $array) || in_array($var1, $array)){
  //do here
}

Output:- https://eval.in/914351

Note:- If you can clarify more about all your variables and what conditions you want for all those variables, you will get more accurate answer


问:
How do I remove the dots in LineChartView iOS charts
I'm learning ios-charts. I was using the tutorial found here. The first picture shows the result I am getting. How do you remove the blue circle dots so that it only shows a smooth line like what is shown in the second picture?

Here is snippet of the code

```<code>import UIKit
import Charts

class ChartsViewController: UIViewController {

@IBOutlet weak var lineChartView: LineChartView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
    let unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0]

    setChart(months, values: unitsSold)

}

func setChart(dataPoints: [String], values: [Double]) {

    var dataEntries: [ChartDataEntry] = []

    for i in 0..<dataPoints.count {
        let dataEntry = ChartDataEntry(value: values[i], xIndex: i)
        dataEntries.append(dataEntry)
    }

    let lineChartDataSet = LineChartDataSet(yVals: dataEntries, label: "Units Sold")
    let lineChartData = LineChartData(xVals: dataPoints, dataSet: lineChartDataSet)
    lineChartView.data = lineChartData

}

}
</code>```

答:
to remove circle in a line

```<code>lineChartDataSet.drawCirclesEnabled = false
</code>```

to remove value alone in a circle

```<code>lineChartData.drawValuesEnabled = false
</code>```

Body:
I'm learning ios-charts. I was using the tutorial found here. The first picture shows the result I am getting. How do you remove the blue circle dots so that it only shows a smooth line like what is shown in the second picture?

Here is snippet of the code

import UIKit
import Charts

class ChartsViewController: UIViewController {

@IBOutlet weak var lineChartView: LineChartView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
    let unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0]

    setChart(months, values: unitsSold)

}

func setChart(dataPoints: [String], values: [Double]) {

    var dataEntries: [ChartDataEntry] = []

    for i in 0..<dataPoints.count {
        let dataEntry = ChartDataEntry(value: values[i], xIndex: i)
        dataEntries.append(dataEntry)
    }

    let lineChartDataSet = LineChartDataSet(yVals: dataEntries, label: "Units Sold")
    let lineChartData = LineChartData(xVals: dataPoints, dataSet: lineChartDataSet)
    lineChartView.data = lineChartData

}

}

Body:
to remove circle in a line

lineChartDataSet.drawCirclesEnabled = false

to remove value alone in a circle

lineChartData.drawValuesEnabled = false