问:
Spinner Adapter keeps on reverting
The spinner works fine, when clicked it has a drop down menu that has checkboxes next to it. My problem is when I click on a check box it ticks, but when I close the spinner and open it back op again, the box is unticked. I want the boxes to remain checked how can I do this?
Here's my code.

```<code>ArrayList<StateVO> listbtop = new ArrayList<>();
    for (int i = 0; i < btoppings.length; i++) {
        StateVO stateVO = new StateVO();
        stateVO.setTitle(btoppings[i]);
        stateVO.setSelected(false);
        listbtop.add(stateVO);
    }
 MyAdapter myAdapter = new MyAdapter(Guest.this, 0, listbtop);
        spinnerbtop.setAdapter(myAdapter);
</code>```

And Here's my Adapter Class.

```<code>public class MyAdapter extends ArrayAdapter<StateVO> {
    private Context mContext;
    private ArrayList<StateVO> listState;
    private MyAdapter myAdapter;
    private boolean isFromView = false;

    public MyAdapter(Context context, int resource, List<StateVO> objects) {
        super(context, resource, objects);
        this.mContext = context;
        this.listState = (ArrayList<StateVO>) objects;
        this.myAdapter = this;

    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    public View getCustomView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            LayoutInflater layoutInflator = LayoutInflater.from(mContext);
            convertView = layoutInflator.inflate(R.layout.spinner_item, null);
            holder = new ViewHolder();
            holder.mTextView = (TextView) convertView.findViewById(R.id.text);
            holder.mCheckBox = (CheckBox) convertView.findViewById(R.id.checkbox);
            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.mTextView.setText(listState.get(position).getTitle());
        // To check weather checked event fire from getview() or user input
        isFromView = true;
        holder.mCheckBox.setChecked(listState.get(position).isSelected());
        isFromView = false;

        if ((position == 0)) {
            holder.mCheckBox.setVisibility(View.INVISIBLE);
        } else {
            holder.mCheckBox.setVisibility(View.VISIBLE);
        }
        holder.mCheckBox.setTag(position);
        holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                int getPosition = (Integer) buttonView.getTag();

            }
        });
        return convertView;
    }
}
</code>```

答:
You must keep the checked state in your object "StateVO", could you try this implementation of getCustomView ?</p>

```<code>public View getCustomView(final int position, View convertView, ViewGroup parent) {
  final ViewHolder holder;
  if (convertView == null) {
    LayoutInflater layoutInflator = LayoutInflater.from(mContext);
    convertView = layoutInflator.inflate(R.layout.spinner_item, null);
    holder = new ViewHolder();
    holder.mTextView = (TextView) convertView.findViewById(R.id.text);
    holder.mCheckBox = (CheckBox) convertView.findViewById(R.id.checkbox);

    holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        listState.get((Integer) holder.mCheckBox.getTag()).setSelected(isChecked);
      }
    });
    convertView.setTag(holder);
  } else {
    holder = (ViewHolder) convertView.getTag();
  }
  holder.mCheckBox.setTag(position);

  holder.mTextView.setText(listState.get(position).getTitle());
  holder.mCheckBox.setChecked(listState.get(position).isSelected());

  return convertView;
}
</code>```

Title: Spinner Adapter keeps on reverting

Body:
The spinner works fine, when clicked it has a drop down menu that has checkboxes next to it. My problem is when I click on a check box it ticks, but when I close the spinner and open it back op again, the box is unticked. I want the boxes to remain checked how can I do this?
Here's my code.

ArrayList<StateVO> listbtop = new ArrayList<>();
    for (int i = 0; i < btoppings.length; i++) {
        StateVO stateVO = new StateVO();
        stateVO.setTitle(btoppings[i]);
        stateVO.setSelected(false);
        listbtop.add(stateVO);
    }
 MyAdapter myAdapter = new MyAdapter(Guest.this, 0, listbtop);
        spinnerbtop.setAdapter(myAdapter);

And Here's my Adapter Class.

public class MyAdapter extends ArrayAdapter<StateVO> {
    private Context mContext;
    private ArrayList<StateVO> listState;
    private MyAdapter myAdapter;
    private boolean isFromView = false;

    public MyAdapter(Context context, int resource, List<StateVO> objects) {
        super(context, resource, objects);
        this.mContext = context;
        this.listState = (ArrayList<StateVO>) objects;
        this.myAdapter = this;

    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    public View getCustomView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            LayoutInflater layoutInflator = LayoutInflater.from(mContext);
            convertView = layoutInflator.inflate(R.layout.spinner_item, null);
            holder = new ViewHolder();
            holder.mTextView = (TextView) convertView.findViewById(R.id.text);
            holder.mCheckBox = (CheckBox) convertView.findViewById(R.id.checkbox);
            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.mTextView.setText(listState.get(position).getTitle());
        // To check weather checked event fire from getview() or user input
        isFromView = true;
        holder.mCheckBox.setChecked(listState.get(position).isSelected());
        isFromView = false;

        if ((position == 0)) {
            holder.mCheckBox.setVisibility(View.INVISIBLE);
        } else {
            holder.mCheckBox.setVisibility(View.VISIBLE);
        }
        holder.mCheckBox.setTag(position);
        holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                int getPosition = (Integer) buttonView.getTag();

            }
        });
        return convertView;
    }
}

Body:
You must keep the checked state in your object "StateVO", could you try this implementation of getCustomView ?

public View getCustomView(final int position, View convertView, ViewGroup parent) {
  final ViewHolder holder;
  if (convertView == null) {
    LayoutInflater layoutInflator = LayoutInflater.from(mContext);
    convertView = layoutInflator.inflate(R.layout.spinner_item, null);
    holder = new ViewHolder();
    holder.mTextView = (TextView) convertView.findViewById(R.id.text);
    holder.mCheckBox = (CheckBox) convertView.findViewById(R.id.checkbox);

    holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        listState.get((Integer) holder.mCheckBox.getTag()).setSelected(isChecked);
      }
    });
    convertView.setTag(holder);
  } else {
    holder = (ViewHolder) convertView.getTag();
  }
  holder.mCheckBox.setTag(position);

  holder.mTextView.setText(listState.get(position).getTitle());
  holder.mCheckBox.setChecked(listState.get(position).isSelected());

  return convertView;
}


来源: stackexchange

问:
Does assigning objects to null in Java impact garbage collection?
Does assigning an unused object reference to null in Java improve the garbage collection process in any measurable way?

My experience with Java (and C#) has taught me that is often counter intuitive to try and outsmart the virtual machine or JIT compiler, but I've seen co-workers use this method and I am curious if this is a good practice to pick up or one of those voodoo programming superstitions?

答:
Explicitly setting a reference to null instead of just letting the variable go out of scope, does not help the garbage collector, unless the object held is very large, where setting it to null as soon as you are done with is a good idea.

Generally setting references to null, mean to the READER of the code that this object is completely done with and should not be concerned about any more.

A similar effect can be achieved by introducing a narrower scope by putting in an extra set of braces

{
  int l;
  {  // <- here
    String bigThing = ....;
    l = bigThing.length();
  }  // <- and here
}
```

this allows the bigThing to be garbage collected right after leaving the nested braces.

OwnerDisplayName: nemo

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: nemo

Body:
Explicitly setting a reference to null instead of just letting the variable go out of scope, does not help the garbage collector, unless the object held is very large, where setting it to null as soon as you are done with is a good idea.

Generally setting references to null, mean to the READER of the code that this object is completely done with and should not be concerned about any more.

A similar effect can be achieved by introducing a narrower scope by putting in an extra set of braces

{
  int l;
  {  // <- here
    String bigThing = ....;
    l = bigThing.length();
  }  // <- and here
}

this allows the bigThing to be garbage collected right after leaving the nested braces.

OwnerDisplayName: Thorbjørn Ravn Andersen

ContentLicense: CC BY-SA 4.0


问:
Mock android Patterns with mockito
I want validate an email with some code provided by Android.

Here is the code I want to mock :

```<code> if(!Patterns.EMAIL_ADDRESS.matcher(email).matches())
      throw new InvalidPhoneException(phone);
</code>```

In my test file :

```<code>@RunWith(PowerMockRunner.class)
@PrepareForTest({ Patterns.class })
public class UserTest {

    @Before
    public void mockValidator() {
        mockStatic(Patterns.class);
        when(Patterns.EMAIL_ADDRESS.matcher(any(String.class)).matches()).thenReturn(true);
    }
</code>```

I got this error when I launch the tests :

```<code>java.lang.NullPointerException
    at ch.mycompany.myapp.model.UserTest.mockValidator(UserTest.java:59)
</code>```

EDIT 1 :

I tried :

```<code>    mockStatic(Patterns.class);
    Field field = PowerMockito.field(Patterns.class, "EMAIL_ADDRESS");
    field.set(Patterns.class, mock(Pattern.class));

    // prepare matcher
    Matcher matcher = mock(Matcher.class);
    when(matcher.matches())
            .thenReturn(true);

    // final mock
    when(Patterns.EMAIL_ADDRESS.matcher(any(String.class)))
            .thenReturn(matcher);
</code>```

But when I do that, my code (Patterns.EMAIL_ADDRESS.matcher(email).matches())
return always false. This is confusing.

答: Using Robolectric will save you lot of headaches in this kind of situation.</p>

Title: Mock android Patterns with mockito

Body:
I want validate an email with some code provided by Android.

Here is the code I want to mock :

 if(!Patterns.EMAIL_ADDRESS.matcher(email).matches())
      throw new InvalidPhoneException(phone);

In my test file :

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Patterns.class })
public class UserTest {

    @Before
    public void mockValidator() {
        mockStatic(Patterns.class);
        when(Patterns.EMAIL_ADDRESS.matcher(any(String.class)).matches()).thenReturn(true);
    }

I got this error when I launch the tests :

java.lang.NullPointerException
    at ch.mycompany.myapp.model.UserTest.mockValidator(UserTest.java:59)

EDIT 1 :

I tried :

    mockStatic(Patterns.class);
    Field field = PowerMockito.field(Patterns.class, "EMAIL_ADDRESS");
    field.set(Patterns.class, mock(Pattern.class));

    // prepare matcher
    Matcher matcher = mock(Matcher.class);
    when(matcher.matches())
            .thenReturn(true);

    // final mock
    when(Patterns.EMAIL_ADDRESS.matcher(any(String.class)))
            .thenReturn(matcher);

But when I do that, my code (Patterns.EMAIL_ADDRESS.matcher(email).matches())
return always false. This is confusing.


问:
Can't connect to Spark thriftserver using JDBC
I followed Spark instructions for starting a thrift JDBC server:

```
$ ./spark-2.1.1-bin-hadoop2.7/sbin/start-thriftserver.sh
```

I can connect to it ok from beeline:

```
$ ./spark-2.1.1-bin-hadoop2.7/bin/beeline -u 'jdbc:hive2://localhost:10000'
Connecting to jdbc:hive2://localhost:10000
log4j:WARN No appenders could be found for logger (org.apache.hive.jdbc.Utils).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Connected to: Spark SQL (version 2.1.1)
Driver: Hive JDBC (version 1.2.1.spark2)
Transaction isolation: TRANSACTION_REPEATABLE_READ
Beeline version 1.2.1.spark2 by Apache Hive
0: jdbc:hive2://localhost:10000>
```

However, trying to connect from DataGrip using JDBC and the same connection string, I get an error:

```
[2017-07-07 16:46:57] java.lang.ClassNotFoundException: org.apache.thrift.transport.TTransportException
[2017-07-07 16:46:57]   at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
[2017-07-07 16:46:57]   at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
[2017-07-07 16:46:57]   at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
[2017-07-07 16:46:57]   at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
[2017-07-07 16:46:57]   at org.apache.hive.jdbc.HiveDriver.connect(HiveDriver.java:105)
[2017-07-07 16:46:57]   at com.intellij.database.remote.jdbc.impl.RemoteDriverImpl.connect(RemoteDriverImpl.java:27)
[2017-07-07 16:46:57]   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[2017-07-07 16:46:57]   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[2017-07-07 16:46:57]   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[2017-07-07 16:46:57]   at java.lang.reflect.Method.invoke(Method.java:498)
[2017-07-07 16:46:57]   at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:324)
[2017-07-07 16:46:57]   at sun.rmi.transport.Transport$1.run(Transport.java:200)
[2017-07-07 16:46:57]   at sun.rmi.transport.Transport$1.run(Transport.java:197)
[2017-07-07 16:46:57]   at java.security.AccessController.doPrivileged(Native Method)
[2017-07-07 16:46:57]   at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
[2017-07-07 16:46:57]   at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
[2017-07-07 16:46:57]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
[2017-07-07 16:46:57]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
[2017-07-07 16:46:57]   at java.security.AccessController.doPrivileged(Native Method)
[2017-07-07 16:46:57]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
[2017-07-07 16:46:57]   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
[2017-07-07 16:46:57]   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
[2017-07-07 16:46:57]   at java.lang.Thread.run(Thread.java:745) (no stack trace)
```

I configured DataGrip to use the JDBC library hive-jdbc-1.2.1.spark2.jar from the spark installation folder.

答: After adding all *.jar files from the spark/jars folder to the "JDBC drivers" window in DataGrip, it works! Not sure which of those libraries were required, but trial-and-error tells me that many of them are!

Body:
I followed Spark instructions for starting a thrift JDBC server:

$ ./spark-2.1.1-bin-hadoop2.7/sbin/start-thriftserver.sh

I can connect to it ok from beeline:

$ ./spark-2.1.1-bin-hadoop2.7/bin/beeline -u 'jdbc:hive2://localhost:10000'
Connecting to jdbc:hive2://localhost:10000
log4j:WARN No appenders could be found for logger (org.apache.hive.jdbc.Utils).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Connected to: Spark SQL (version 2.1.1)
Driver: Hive JDBC (version 1.2.1.spark2)
Transaction isolation: TRANSACTION_REPEATABLE_READ
Beeline version 1.2.1.spark2 by Apache Hive
0: jdbc:hive2://localhost:10000>

However, trying to connect from DataGrip using JDBC and the same connection string, I get an error:

[2017-07-07 16:46:57] java.lang.ClassNotFoundException: org.apache.thrift.transport.TTransportException
[2017-07-07 16:46:57]   at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
[2017-07-07 16:46:57]   at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
[2017-07-07 16:46:57]   at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
[2017-07-07 16:46:57]   at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
[2017-07-07 16:46:57]   at org.apache.hive.jdbc.HiveDriver.connect(HiveDriver.java:105)
[2017-07-07 16:46:57]   at com.intellij.database.remote.jdbc.impl.RemoteDriverImpl.connect(RemoteDriverImpl.java:27)
[2017-07-07 16:46:57]   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[2017-07-07 16:46:57]   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[2017-07-07 16:46:57]   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[2017-07-07 16:46:57]   at java.lang.reflect.Method.invoke(Method.java:498)
[2017-07-07 16:46:57]   at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:324)
[2017-07-07 16:46:57]   at sun.rmi.transport.Transport$1.run(Transport.java:200)
[2017-07-07 16:46:57]   at sun.rmi.transport.Transport$1.run(Transport.java:197)
[2017-07-07 16:46:57]   at java.security.AccessController.doPrivileged(Native Method)
[2017-07-07 16:46:57]   at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
[2017-07-07 16:46:57]   at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
[2017-07-07 16:46:57]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
[2017-07-07 16:46:57]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
[2017-07-07 16:46:57]   at java.security.AccessController.doPrivileged(Native Method)
[2017-07-07 16:46:57]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
[2017-07-07 16:46:57]   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
[2017-07-07 16:46:57]   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
[2017-07-07 16:46:57]   at java.lang.Thread.run(Thread.java:745) (no stack trace)

I configured DataGrip to use the JDBC library hive-jdbc-1.2.1.spark2.jar from the spark installation folder.


问:
String comparision not working when compared against an item(concatenated string) in C# ArrayList
Kindly explain what's going on with this below code (//DOESN'T WORK sections)
I know it will work if I rather use Equals() instead of == operator. But I am missing some understanding here. Thanks.

EDIT: My goal here is not to make it work, rather want to understand what's going on at compiler/runtime level in detail.

```<code>        string first = "string1";
        string full = first + " string2";

        Debug.Assert(full == "string1 string2", "Expected to be same.");//WORKS
        Debug.Assert(first + " string2" == "string1 string2", "Expected to be same.");//WORKS

        var list = new ArrayList();
        list.Add(full);
        list.Add(first + " string2");

        Debug.Assert(list[0] == "string1 string2", "Expected to be same.");//DOESN'T WORK
        Debug.Assert(list[1] == "string1 string2", "Expected to be same.");//DOESN'T WORK

        list.Add("string1 string2");
        Debug.Assert(list[2] == "string1 string2", "Expected to be same.");//WORKS
</code>```

答:
Maybe because type of list[0] is Object.
If add ToString() method like this:

Debug.Assert(list[0].ToString() == "string1 string2", "Expected to be same."); it should work

Body:
Kindly explain what's going on with this below code (//DOESN'T WORK sections)
I know it will work if I rather use Equals() instead of == operator. But I am missing some understanding here. Thanks.

EDIT: My goal here is not to make it work, rather want to understand what's going on at compiler/runtime level in detail.

        string first = "string1";
        string full = first + " string2";

        Debug.Assert(full == "string1 string2", "Expected to be same.");//WORKS
        Debug.Assert(first + " string2" == "string1 string2", "Expected to be same.");//WORKS

        var list = new ArrayList();
        list.Add(full);
        list.Add(first + " string2");

        Debug.Assert(list[0] == "string1 string2", "Expected to be same.");//DOESN'T WORK
        Debug.Assert(list[1] == "string1 string2", "Expected to be same.");//DOESN'T WORK

        list.Add("string1 string2");
        Debug.Assert(list[2] == "string1 string2", "Expected to be same.");//WORKS


问:
Uncaught TypeError: a.customFilter is not a function with ngAnimate
I'm working on an AngularJS application, and I tried to add Angular Animate.

Angular Route didn't cause any problem, but it seems Angular Animate is not compatible with something in my app.

I load the libs in this order:

```<code><script type="text/javascript" src="../node_modules/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="../node_modules/angular/angular.min.js"></script>
<script type="text/javascript" src="../node_modules/angular-animate/angular-animate.min.js"></script>
<script type="text/javascript" src="../node_modules/angular-route/angular-route.min.js"></script>
</code>```

And use them in my app.js:

```<code>var app = angular.module('tictactoe', ['ngRoute', 'ngAnimate']);
</code>```

I'm getting the following error. JQuery and Angular (Vanilla + Route + Animate) have been installed with npm

Dependencies versions:

答:
Use angular version 1.6.5 or downgrade angular-animate version to 1.6.4 It'll solve the issue.
Here's a plunk of some angular app example in which this dependency condition can be verified (just change versions of libraries in cdn link)

https://plnkr.co/edit/v0cLmZvYAC8m1J7JdwHf?p=preview

Body:
I'm working on an AngularJS application, and I tried to add Angular Animate.

Angular Route didn't cause any problem, but it seems Angular Animate is not compatible with something in my app.

I load the libs in this order:

And use them in my app.js:

var app = angular.module('tictactoe', ['ngRoute', 'ngAnimate']);

I'm getting the following error. JQuery and Angular (Vanilla + Route + Animate) have been installed with npm

Dependencies versions:


问:
Distribute user active time blocks subject to total constraint
I am building an agent-based model for product usage. I am trying to develop a function to decide whether the user is using the product at a given time, while incorporating randomness.

So, say we know the user spends a total of 1 hour per day using the product, and we know the average distribution of this time (e.g., most used at 6-8pm).

How can I generate a set of usage/non-usage times (i.e., during each 10 minute block is the user active or not) while ensuring that at the end of the day the total active time sums to one hour.

In most cases I would just run the distributor without concern for the total, and then at the end normalize by making it proportional to the total target time so the total was 1 hour. However, I can't do that because time blocks must be 10 minutes. I think this is a different question because I'm really not computing time ranges, I'm computing booleans to associate with different 10 minute time blocks (e.g., the user was/was not active during a given block).

Is there a standard way to do this?

答:
I did some more thinking and figured it out, if anyone else is looking at this.

The approach to take is this: You know the allowed number n of 10-minute time blocks for a given agent.

Iterate n times, and on each iteration select a time block out of the day subject to your activity distribution function.

Main point is to iterate over the number of time blocks you want to place, not over the entire day.


问:
Setting threshold on max number of classes selected/activated on click on multiple divs/id's
I've been working on a skill tree 'persay' and I ran into an interesting problem.

I have my code setup to allow a user to click a talent to show that particular talent has been selected up to a max number of 4 talents total. Once you have selected 4 talents you have to deselect a talent to select a different one.

My problem comes when I duplicate the talent tree for a second talent tree on the same page(for a second hero/class essentially or a second party member out of your party). I can't figure out how to make the same 'threshold of a max of 4 talents' on other skill trees standalone. What happens is that they all share the same threshold across all trees. I have tried making separate id's each and even changing the variable names within each function.

var skillTotal = 0;
var skillSelected = 0;

$( "#selectable01>li.skill-slot" ).bind( "click", function ( e ) {
    var threshold = 4;
        var price = 1;
        if ($(this).hasClass('selected')) {
                skillTotal = skillTotal - 1;
                skillSelected--;
                $(this).toggleClass('selected');
        }
        else if (price + skillTotal <= threshold) {
                skillTotal = skillTotal + price;
                skillSelected++;
                $(this).toggleClass('selected');
        }
});

$( "#selectable02>li.skill-slot" ).bind( "click", function ( e ) {
    var threshold = 4;
        var price = 1;
        if ($(this).hasClass('selected')) {
                skillTotal = skillTotal - 1;
                skillSelected--;
                $(this).toggleClass('selected');
        }
        else if (price + skillTotal <= threshold) {
                skillTotal = skillTotal + price;
                skillSelected++;
                $(this).toggleClass('selected');
        }
});

/* NOT USING THIS CURRENTLY
$( "#campSelectable>li.camp-slot" ).bind( "click", function ( e ) {
    var campThreshold = 3;
        var campPrice = 1;
        if ($(this).hasClass('selected')) {
                campTotal = campTotal - campPrice;
                selectedCamp--;
                $(this).toggleClass('selected');
        }
        else if (campPrice + campTotal <= campThreshold) {
                campTotal = campTotal + campPrice;
                selectedCamp++;
                $(this).toggleClass('selected');
        }
}); */```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.skill-slot, .camp-slot{
  border:2px solid black;
  width:100px;
  margin: 5px;
  opacity: .4;
}

.skill-slot:hover, .camp-slot:hover {
  opacity: 1;
}

.raffle-slot.taken{
  background:red;
}
.selected{
  background: rgb(255, 128, 128);
  opacity: 1;
}</code>```

1

2

3

4

5

6

7

1

2

3

4

5

6

7

```

Here are the things I have tried:
Initially my identifier was : $( "#calc>ol>li.skill-slot" ).on so I began adding additional id's to drill down further and make sure that my functions were targeting specific div's, so I moved to this: $( "#calc>#selectable01>li.skill-slot" ).on and $( "#calc>#selectable02>li.skill-slot" ).on

The reason I didn't want to target a second ID is because I'll be using templates that are appended to the #calc div effectively replacing the current roster with a new one. I also did this for testing to see if I could resolve the issue by making them their own individual id's, which didn't work.

答: You're storing skillSelected outside of the event handlers so each event handler is reading that variable. You might need to get a running total of how many are selected each time the event handler is triggered.

Body:
I've been working on a skill tree 'persay' and I ran into an interesting problem.

I have my code setup to allow a user to click a talent to show that particular talent has been selected up to a max number of 4 talents total. Once you have selected 4 talents you have to deselect a talent to select a different one.

My problem comes when I duplicate the talent tree for a second talent tree on the same page(for a second hero/class essentially or a second party member out of your party). I can't figure out how to make the same 'threshold of a max of 4 talents' on other skill trees standalone. What happens is that they all share the same threshold across all trees. I have tried making separate id's each and even changing the variable names within each function.

var skillTotal = 0;
var skillSelected = 0;

$( "#selectable01>li.skill-slot" ).bind( "click", function ( e ) {
    var threshold = 4;
        var price = 1;
        if ($(this).hasClass('selected')) {
                skillTotal = skillTotal - 1;
                skillSelected--;
                $(this).toggleClass('selected');
        }
        else if (price + skillTotal <= threshold) {
                skillTotal = skillTotal + price;
                skillSelected++;
                $(this).toggleClass('selected');
        }
});

$( "#selectable02>li.skill-slot" ).bind( "click", function ( e ) {
    var threshold = 4;
        var price = 1;
        if ($(this).hasClass('selected')) {
                skillTotal = skillTotal - 1;
                skillSelected--;
                $(this).toggleClass('selected');
        }
        else if (price + skillTotal <= threshold) {
                skillTotal = skillTotal + price;
                skillSelected++;
                $(this).toggleClass('selected');
        }
});

/* NOT USING THIS CURRENTLY
$( "#campSelectable>li.camp-slot" ).bind( "click", function ( e ) {
    var campThreshold = 3;
        var campPrice = 1;
        if ($(this).hasClass('selected')) {
                campTotal = campTotal - campPrice;
                selectedCamp--;
                $(this).toggleClass('selected');
        }
        else if (campPrice + campTotal <= campThreshold) {
                campTotal = campTotal + campPrice;
                selectedCamp++;
                $(this).toggleClass('selected');
        }
}); */

.skill-slot, .camp-slot{
  border:2px solid black;
  width:100px;
  margin: 5px;
  opacity: .4;
}

.skill-slot:hover, .camp-slot:hover {
  opacity: 1;
}

.raffle-slot.taken{
  background:red;
}
.selected{
  background: rgb(255, 128, 128);
  opacity: 1;
}

1

2

3

4

5

6

7

1

2

3

4

5

6

7

Here are the things I have tried:
Initially my identifier was : $( "#calc>ol>li.skill-slot" ).on so I began adding additional id's to drill down further and make sure that my functions were targeting specific div's, so I moved to this: $( "#calc>#selectable01>li.skill-slot" ).on and $( "#calc>#selectable02>li.skill-slot" ).on

The reason I didn't want to target a second ID is because I'll be using templates that are appended to the #calc div effectively replacing the current roster with a new one. I also did this for testing to see if I could resolve the issue by making them their own individual id's, which didn't work.


问:
Python + Q (KDB) - which tools are easy to use and well maintained
From a thread dating a few years back I found some options to integrate python and kdb, namely

qpt

Dan's tools

PyQ

qPython

The last two seem to be the only ones actively updated at the moment. My question goes to the folks that actually use any (and ideally tried several) of these tools. From your experience, which of the two latter ones is more suitable for me. Selection criteria would be (in that order)

ease of use (I am new to q, ideally I would do more work in python than in q)

documentation (seems to be generally not great on anything kdb)

python 3.x support

speed

If I completely missed a tool that fits my requirements, please let me know. I am aware of threads that raise similar questions, but I am looking for a 2017 answer, not 2015.

答:
Exxeleron's qPython "is a Python library providing support for interprocess communication between Python and kdb+ processes."  While the same functionality is available from PyQ, PyQ offers much more than just IPC.

PyQ is a full-featured Python interpreter running inside a kdb+ instance.  For a Python programmer, PyQ gives a direct access to kdb+ data without any need to program in q. For a q programmer, PyQ offers an easy access to a rich set of computational and visualization libraries that Python is famous for.

To give an example, here is a linear interpolation function inp written in q:

```<code>inp:{y[i]+(z-x i)*(deltas[y]%deltas x)1+i:x bin z}
</code>```

It takes three arguments: x and y are coordinates of the known data points and z is x-coordinates of the interpolated values. It returns the  y-coordinates of the interpolated values. The same function can be written in PyQ using pure Python syntax:

```<code>def inp(x, y, z):
    slope = y.deltas / x.deltas
    i = x.bin(z)
    return y[i] + (z - x[i]) * slope[i+1]
</code>```

If you prepare the data in q

```<code>x:0.1*til 10
y:x - x * x
z:5?1f
</code>```

and call either Python or q implementation, you will get the same result.  At the PyQ's Python prompt this can be verified as follows:

```<code>>>> inp(q.x, q.y, q.z) == q.inp(q.x, q.y, q.z)
True
</code>```

Of course, an experienced Python programmer would not need to write such a function from scratch because NumPy already has numpy.interp which does the same and more. If, as a q programmer, you want to use numpy.interp from q, all you need is a simple wrapper that converts the result to a K object before returning it.  This is how it can be done at the q) prompt

```<code>q)p)import numpy; from pyq import q, K
q)p)def inp2(x, y, z): return K(numpy.interp(z, x, y))
q)p)q.inp2 = inp2
</code>```

And now, inp2 is ready to use:

```<code>q)inp[x;y;z] ~ inp2(x;y;z)
1b
</code>```

Since PyQ runs inside kdb+, it gets its IPC implementation for free.  For example, I can open a connection to the remote server at port 8888 and ask for its local time in two lines of code:

```<code>>>> h = q.hopen('::8888')
>>> h('.z.P')
k('2017.07.07D17:15:19.261285000')
</code>```

However, most of the tasks can be accomplished in PyQ without any IPC (or even copying) at all because all your kdb+ data is already in the same process as your Python code.

To cover the OP's rubrics, on the ease of use, qPython being a pure Python library may be easier to install, but PyQ programing is often easier because it does not require a separate kdb+ server.  PyQ documentation is comparable in quality to that of qPython.  PyQ offered python 3.x support since its version 3.0.1 and Python 3.1.  Currently (2017) it is actively tested with Python 2.7, 3.5 and 3.6.  Speed comparison would not be fair because PyQ has direct access to kdb+ data and does not require IPC, so it can accomplish many tasks 100x faster than qPython.

Disclaimer: I am the author of PyQ.

Body:
Exxeleron's qPython "is a Python library providing support for interprocess communication between Python and kdb+ processes."  While the same functionality is available from PyQ, PyQ offers much more than just IPC.

PyQ is a full-featured Python interpreter running inside a kdb+ instance.  For a Python programmer, PyQ gives a direct access to kdb+ data without any need to program in q. For a q programmer, PyQ offers an easy access to a rich set of computational and visualization libraries that Python is famous for.

To give an example, here is a linear interpolation function inp written in q:

inp:{y[i]+(z-x i)*(deltas[y]%deltas x)1+i:x bin z}

It takes three arguments: x and y are coordinates of the known data points and z is x-coordinates of the interpolated values. It returns the  y-coordinates of the interpolated values. The same function can be written in PyQ using pure Python syntax:

def inp(x, y, z):
    slope = y.deltas / x.deltas
    i = x.bin(z)
    return y[i] + (z - x[i]) * slope[i+1]

If you prepare the data in q

x:0.1*til 10
y:x - x * x
z:5?1f

and call either Python or q implementation, you will get the same result.  At the PyQ's Python prompt this can be verified as follows:

>>> inp(q.x, q.y, q.z) == q.inp(q.x, q.y, q.z)
True

Of course, an experienced Python programmer would not need to write such a function from scratch because NumPy already has numpy.interp which does the same and more. If, as a q programmer, you want to use numpy.interp from q, all you need is a simple wrapper that converts the result to a K object before returning it.  This is how it can be done at the q) prompt

q)p)import numpy; from pyq import q, K
q)p)def inp2(x, y, z): return K(numpy.interp(z, x, y))
q)p)q.inp2 = inp2

And now, inp2 is ready to use:

q)inp[x;y;z] ~ inp2(x;y;z)
1b

Since PyQ runs inside kdb+, it gets its IPC implementation for free.  For example, I can open a connection to the remote server at port 8888 and ask for its local time in two lines of code:

>>> h = q.hopen('::8888')
>>> h('.z.P')
k('2017.07.07D17:15:19.261285000')

However, most of the tasks can be accomplished in PyQ without any IPC (or even copying) at all because all your kdb+ data is already in the same process as your Python code.

To cover the OP's rubrics, on the ease of use, qPython being a pure Python library may be easier to install, but PyQ programing is often easier because it does not require a separate kdb+ server.  PyQ documentation is comparable in quality to that of qPython.  PyQ offered python 3.x support since its version 3.0.1 and Python 3.1.  Currently (2017) it is actively tested with Python 2.7, 3.5 and 3.6.  Speed comparison would not be fair because PyQ has direct access to kdb+ data and does not require IPC, so it can accomplish many tasks 100x faster than qPython.

Disclaimer: I am the author of PyQ.


问:
What does this batch code exactly do?
I just surfed internet to find a function in batch, which colorizes the text. This is the code:

```<code>:Color
:: v20 deprecated.
:: Arguments: hexColor text [\n]
:: Supported in windows XP, 7, 8.
:: In XP extended ascii characters are printed as dots.
:: For print quotes, use empty text.
SetLocal enableExtensions EnableDelayedExpansion
Set "Text=%~2"
If Not Defined Text (Set Text=^")
Subst `: "!Temp!" >Nul &`: &Cd \
If Not Exist `.7 (
Echo(|(Pause >Nul &Findstr "^" >`)
Set /P "=." >>` <Nul
For /F "delims=;" %%# In (
'"Prompt $H;&For %%_ In (_) Do Rem"') Do (
Set /P "=%%#%%#%%#" <Nul >`.3
Set /P "=%%#%%#%%#%%#%%#" <Nul >`.5
Set /P "=%%#%%#%%#%%#%%#%%#%%#" <Nul >`.7))
Set /P "LF=" <` &Set "LF=!LF:~0,1!"
For %%# in ("!LF!") Do For %%_ In (
\ / :) Do Set "Text=!Text:%%_=%%~#%%_%%~#!"
For /F delims^=^ eol^= %%# in ("!Text!") Do (
If #==#! SetLocal DisableDelayedExpansion
If \==%%# (Findstr /A:%~1 . \` Nul
Type `.3) Else If /==%%# (Findstr /A:%~1 . /.\` Nul
Type `.5) Else (Echo %%#\..\`>`.dat
Findstr /F:`.dat /A:%~1 .
Type `.7))
If "\n"=="%~3" (Echo()
Goto :Eof
</code>```

Can anyone please explain how is this working? I would really want to know what does each phrase do and how it participates in printing out color text.

P.S. I know most of the stuff what's happening there, I just don't know how it makes the console print out text in color and why does it create files in %Temp% directory.

I would like for the explanation to be step by step and easy to understand please.

Thank you!

答:
I'm not sure what is going on but the easiest way for me is with powershell:

Put this at the top after @echo off

```<code>setlocal EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
set "DEL=%%a"
)
rem Prepare a file "X" with only one dot
<nul > X set /p ".=."
</code>```

(It will create a file "x" that will stick around. Anoying but nothing much.

Then put this at the complete bottom of the script.

```<code>:colorEcho
set "param=^%~2" !
set "param=!param:"=\"!"
findstr /p /A:%1 "." "!param!\..\X" nul
<nul set /p ".=%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%"
exit /b
</code>```

Then use this format to make colored text:

```<code>call :ColorEcho 81 "text" &echo.
</code>```

the 81 is the color code for cmd. In the command prompt run color /? and you'll find the color codes there. The first one is the background the second is the text.

Title: What does this batch code exactly do?

Body:
I just surfed internet to find a function in batch, which colorizes the text. This is the code:

:Color
:: v20 deprecated.
:: Arguments: hexColor text [\n]
:: Supported in windows XP, 7, 8.
:: In XP extended ascii characters are printed as dots.
:: For print quotes, use empty text.
SetLocal enableExtensions EnableDelayedExpansion
Set "Text=%~2"
If Not Defined Text (Set Text=^")
Subst `: "!Temp!" >Nul &`: &Cd \
If Not Exist `.7 (
Echo(|(Pause >Nul &Findstr "^" >`)
Set /P "=." >>` <Nul
For /F "delims=;" %%# In (
'"Prompt $H;&For %%_ In (_) Do Rem"') Do (
Set /P "=%%#%%#%%#" <Nul >`.3
Set /P "=%%#%%#%%#%%#%%#" <Nul >`.5
Set /P "=%%#%%#%%#%%#%%#%%#%%#" <Nul >`.7))
Set /P "LF=" <` &Set "LF=!LF:~0,1!"
For %%# in ("!LF!") Do For %%_ In (
\ / :) Do Set "Text=!Text:%%_=%%~#%%_%%~#!"
For /F delims^=^ eol^= %%# in ("!Text!") Do (
If #==#! SetLocal DisableDelayedExpansion
If \==%%# (Findstr /A:%~1 . \` Nul
Type `.3) Else If /==%%# (Findstr /A:%~1 . /.\` Nul
Type `.5) Else (Echo %%#\..\`>`.dat
Findstr /F:`.dat /A:%~1 .
Type `.7))
If "\n"=="%~3" (Echo()
Goto :Eof

Can anyone please explain how is this working? I would really want to know what does each phrase do and how it participates in printing out color text.

P.S. I know most of the stuff what's happening there, I just don't know how it makes the console print out text in color and why does it create files in %Temp% directory.

I would like for the explanation to be step by step and easy to understand please.

Thank you!

Body:
I'm not sure what is going on but the easiest way for me is with powershell:

Put this at the top after @echo off

setlocal EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
set "DEL=%%a"
)
rem Prepare a file "X" with only one dot
<nul > X set /p ".=."

(It will create a file "x" that will stick around. Anoying but nothing much.

Then put this at the complete bottom of the script.

:colorEcho
set "param=^%~2" !
set "param=!param:"=\"!"
findstr /p /A:%1 "." "!param!\..\X" nul
<nul set /p ".=%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%"
exit /b

Then use this format to make colored text:

call :ColorEcho 81 "text" &echo.

the 81 is the color code for cmd. In the command prompt run color /? and you'll find the color codes there. The first one is the background the second is the text.


问:
How can I load a .csv file in java code to test with weka?
I have a model obtained from weka classifier and I want to test it in java code, But when I read instances, an error appear:

```<code>Exception in thread "main" java.io.IOException: keyword @relation expected, read Token[Word], line 1
at weka.core.Instances.errms(Instances.java:1863)
at weka.core.Instances.readHeader(Instances.java:1740)
at weka.core.Instances.<init>(Instances.java:119)
at licenta1.LoadModelWeka.main(LoadModelWeka.java:18)
</code>```

My code is:

```<code>package licenta1;

import weka.core.Instances;
import weka.classifiers.bayes.NaiveBayes;
import weka.classifiers.trees.J48;
import weka.classifiers.Evaluation;

import java.util.Random;
import java.io.BufferedReader;
import java.io.FileReader ;

public class LoadModelWeka
{
   public static void main(String[] args) throws Exception {
   // training
      BufferedReader reader = null;
      reader=new BufferedReader(new FileReader("D:\\aaaaaaaaaaaaaaaaaaaaaa\\Licenta\\BioArtLicTrainSetTask1.csv"));
      Instances train =new Instances (reader);
      train.setClassIndex(0);
      reader.close();

      NaiveBayes nb = new NaiveBayes();
      nb.buildClassifier(train);
      Evaluation eval = new Evaluation(train);
      eval.crossValidateModel(nb, train, 10 , new Random(1));

      System.out.println(eval.toSummaryString("\n Results \n=====\n",true));
      System.out.println(eval.fMeasure(1)+" "+eval.precision(1)+" "+eval.recall(1)+" ");
   }
}
</code>```

Can somebody help me?
Mt training set is in .csv format

答:
Instead of using Buffered Reader you can try

```<code>DataSource source = new DataSource("/some/where/data.arff");
</code>```

For more information visit this link http://weka.wikispaces.com/Use+WEKA+in+your+Java+code

Body:
I have a model obtained from weka classifier and I want to test it in java code, But when I read instances, an error appear:

Exception in thread "main" java.io.IOException: keyword @relation expected, read Token[Word], line 1
at weka.core.Instances.errms(Instances.java:1863)
at weka.core.Instances.readHeader(Instances.java:1740)
at weka.core.Instances.<init>(Instances.java:119)
at licenta1.LoadModelWeka.main(LoadModelWeka.java:18)

My code is:

package licenta1;

import weka.core.Instances;
import weka.classifiers.bayes.NaiveBayes;
import weka.classifiers.trees.J48;
import weka.classifiers.Evaluation;

import java.util.Random;
import java.io.BufferedReader;
import java.io.FileReader ;

public class LoadModelWeka
{
   public static void main(String[] args) throws Exception {
   // training
      BufferedReader reader = null;
      reader=new BufferedReader(new FileReader("D:\\aaaaaaaaaaaaaaaaaaaaaa\\Licenta\\BioArtLicTrainSetTask1.csv"));
      Instances train =new Instances (reader);
      train.setClassIndex(0);
      reader.close();

      NaiveBayes nb = new NaiveBayes();
      nb.buildClassifier(train);
      Evaluation eval = new Evaluation(train);
      eval.crossValidateModel(nb, train, 10 , new Random(1));

      System.out.println(eval.toSummaryString("\n Results \n=====\n",true));
      System.out.println(eval.fMeasure(1)+" "+eval.precision(1)+" "+eval.recall(1)+" ");
   }
}

Can somebody help me?
Mt training set is in .csv format

Body:
Instead of using Buffered Reader you can try

DataSource source = new DataSource("/some/where/data.arff");

For more information visit this link http://weka.wikispaces.com/Use+WEKA+in+your+Java+code


问:
Jquery UI Datepicker, beforeShowDay error
I am trying to add days to disable from the server. This is my code so far:

```<code> $("#startDatePicker").datepicker({
        minDate: '+31',
        maxDate: '+12M',
        changeMonth: true,
        showAnim: 'blind',
        dateFormat: 'yy mm dd',
        onSelect: function(dateText, inst) {

            // Capture the Date from User Selection
            var oldDate = new Date(dateText);
            var newDate = new Date(dateText);

            // Compute the Future Limiting Date
            newDate.setDate(newDate.getDate() + 365);

            // Set the Widget Properties
            $("#endDatePicker").datepicker('option', 'minDate', oldDate);
            $("#endDatePickerto").datepicker('option', 'maxDate', newDate);

        }
    });

    $("#endDatePicker").datepicker({
        minDate: '+5',
        maxDate: '+12M',
        changeMonth: true,
        showAnim: 'blind',
        dateFormat: 'yy mm dd',
        onSelect: function(dateText, inst) {

            // Capture the Date from User Selection
            var endDate = new Date(dateText);
            var startDate = new Date(dateText);

            // Compute the Future Limiting Date
            startDate.setDate(startDate.getDate() - 5);

            // Set the Widget Properties
            $("#startDatePicker").datepicker('option', 'minDate', startDate);
            $("#startDatePicker").datepicker('option', 'maxDate', endDate);

        }

    });
</code>```

The picker works fine until i add days to disable. I parse it from a viewbag. Here is the code.

```<code>var NewArray = [];
var array = @Html.Raw(Json.Encode((@ViewBag.GetDates)));
for (var i = 0; i < array.length; i++) {
    NewArray[i] = array[i];
    console.log(NewArray);

}
var parsedDates = [];
for (var i = 0; i < array.length; i++) {
    var d = array[i];
    var unix = +d.replace(/\D/g, '');
    var date = new Date(unix);
    var desDate = date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate();
    parsedDates.push(desDate);
}
console.log(parsedDates);
</code>```

and I add the dates like this to the picker:

```<code>beforeShowDay: function (date) {
            var string = jQuery.datepicker.formatDate('yy mm dd', date);
            return [parsedDates.indexOf(string) === -1];
        }
</code>```

The picker looks like this when everything is added:

What I am doing wrong.

答: Solved It. Had to reconstruct the date string going in to the beforShowDay. After that everything worked. </p>

Body:
I am trying to add days to disable from the server. This is my code so far:

 $("#startDatePicker").datepicker({
        minDate: '+31',
        maxDate: '+12M',
        changeMonth: true,
        showAnim: 'blind',
        dateFormat: 'yy mm dd',
        onSelect: function(dateText, inst) {

            // Capture the Date from User Selection
            var oldDate = new Date(dateText);
            var newDate = new Date(dateText);

            // Compute the Future Limiting Date
            newDate.setDate(newDate.getDate() + 365);

            // Set the Widget Properties
            $("#endDatePicker").datepicker('option', 'minDate', oldDate);
            $("#endDatePickerto").datepicker('option', 'maxDate', newDate);

        }
    });

    $("#endDatePicker").datepicker({
        minDate: '+5',
        maxDate: '+12M',
        changeMonth: true,
        showAnim: 'blind',
        dateFormat: 'yy mm dd',
        onSelect: function(dateText, inst) {

            // Capture the Date from User Selection
            var endDate = new Date(dateText);
            var startDate = new Date(dateText);

            // Compute the Future Limiting Date
            startDate.setDate(startDate.getDate() - 5);

            // Set the Widget Properties
            $("#startDatePicker").datepicker('option', 'minDate', startDate);
            $("#startDatePicker").datepicker('option', 'maxDate', endDate);

        }

    });

The picker works fine until i add days to disable. I parse it from a viewbag. Here is the code.

var NewArray = [];
var array = @Html.Raw(Json.Encode((@ViewBag.GetDates)));
for (var i = 0; i < array.length; i++) {
    NewArray[i] = array[i];
    console.log(NewArray);

}
var parsedDates = [];
for (var i = 0; i < array.length; i++) {
    var d = array[i];
    var unix = +d.replace(/\D/g, '');
    var date = new Date(unix);
    var desDate = date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate();
    parsedDates.push(desDate);
}
console.log(parsedDates);

and I add the dates like this to the picker:

beforeShowDay: function (date) {
            var string = jQuery.datepicker.formatDate('yy mm dd', date);
            return [parsedDates.indexOf(string) === -1];
        }

The picker looks like this when everything is added:

What I am doing wrong.


问:
Could not run elki.sh in mac OSX
In order to use ELKI to do a clustering task, I have downloaded the latest complete release package: elki-0.7.1

The README.PDF says to run elki.sh on OSX. However, after I run the elki.sh with Terminal, it pops the following error:

Error: Could not find or load main class de.lmu.ifi.dbs.elki.application.ELKILauncher

I am sure I have downloaded the complete packages entirely, but still could not run ELKI successfully. Thanks in advance!

答:
I will show below how you can install Elki in macOS, El Capitan Version 10.11.6.

Installation of ELKI in macOS

```<code>brew cask install java

git clone https://github.com/elki-project/elki.git

cd elki

./gradlew shadowJar

./gradlew build

open elki-bundle-0.7.2-SNAPSHOT.jar
</code>```

where you can see the ELKILauncher.

Example that ELKI is working just fine

Background

You don't have to configure any paths, actually. Questions you may want to ask yourself are

Did you build the Elki on the command line?

Do you have the correct Java? You can install it easiest with brew as shown above.

Title: Could not run elki.sh in mac OSX

Body:
I will show below how you can install Elki in macOS, El Capitan Version 10.11.6.

Installation of ELKI in macOS

brew cask install java

git clone https://github.com/elki-project/elki.git

cd elki

./gradlew shadowJar

./gradlew build

open elki-bundle-0.7.2-SNAPSHOT.jar

where you can see the ELKILauncher.

Example that ELKI is working just fine

Background

You don't have to configure any paths, actually. Questions you may want to ask yourself are

Did you build the Elki on the command line?

Do you have the correct Java? You can install it easiest with brew as shown above.


问:
set min length to fields in mysql
hi am new to sql can anyone help me with it.

I want to create a field example code date_type int auto increment with min size 9
that is that number should be 000000001,000000002...000000010....

答:
Use ZEROFILL. Here is an example:

```<code>CREATE TABLE zerofill_test (f1 INT(4) ZEROFILL,f2 INT(4));
INSERT INTO zerofill_test VALUES ( 1, 1 ), (10000, 10000);
</code>```

Here f1 is defined with 'ZEROFILL' of 'int' type and f2 is simple int.
When data is selected with SELECT command it shows you the desired result.

```<code>SELECT * FROM zerofill_test;
 +-------+-------+
 | h     | m     |
 +-------+-------+
 |  0001 |     1 |
 | 10000 | 10000 |
 +-------+-------+
</code>```

For you purpose, the size of int field should be 9 i.e. `date_type int(9) ZEROFILL'

ContentLicense: CC BY-SA 2.5

Title: set min length to fields in mysql

Body:
Use ZEROFILL. Here is an example:

CREATE TABLE zerofill_test (f1 INT(4) ZEROFILL,f2 INT(4));
INSERT INTO zerofill_test VALUES ( 1, 1 ), (10000, 10000);

Here f1 is defined with 'ZEROFILL' of 'int' type and f2 is simple int.
When data is selected with SELECT command it shows you the desired result.

SELECT * FROM zerofill_test;
 +-------+-------+
 | h     | m     |
 +-------+-------+
 |  0001 |     1 |
 | 10000 | 10000 |
 +-------+-------+

For you purpose, the size of int field should be 9 i.e. `date_type int(9) ZEROFILL'


问:
Use a range of values with a variable
I have the following queries;

```<code>$sel_referrals1="SELECT t1.referree AS GEN1, t2.referree as GEN2, t3.referree as GEN3, t4.referree as GEN4, t5.referree as GEN5, t6.referree as GEN6, t7.referree as GEN7, t8.referree as GEN8, t9.referree as GEN9, t10.referree as GEN10, t11.referree as GEN11
                                        FROM referrals AS t1
                                        LEFT JOIN referrals AS t2 ON t2.referrer = t1.referree
                                        LEFT JOIN referrals AS t3 ON t3.referrer = t2.referree
                                        LEFT JOIN referrals AS t4 ON t4.referrer = t3.referree
                                        LEFT JOIN referrals AS t5 ON t5.referrer = t4.referree
                                        LEFT JOIN referrals AS t6 ON t6.referrer = t5.referree
                                        LEFT JOIN referrals AS t7 ON t7.referrer = t6.referree
                                        LEFT JOIN referrals AS t8 ON t8.referrer = t7.referree
                                        LEFT JOIN referrals AS t9 ON t9.referrer = t8.referree
                                        LEFT JOIN referrals AS t10 ON t10.referrer = t9.referree
                                        LEFT JOIN referrals AS t11 ON t11.referrer = t10.referree
                                        WHERE t1.referrer = '{$_SESSION['user']}'";
$selected1 = mysqli_query($conn, $sel_referrals1);
$selected_levels= mysqli_fetch_array($selected1);
</code>```

I wanted to process the results of the query as in the following statement;

```<code>$select_level1="SELECT SUM(amount) FROM topup WHERE user_id IN('{$selected1['GEN1']}')";//The is line 80
 $selected_level1 = mysqli_query($conn,$select_level1);
 $result_level1 = mysqli_fetch_row($selected_level1);
 $level1=number_format($result_level1[0],2);
</code>```

However, i get the following error;

Fatal error: Cannot use object of type mysqli_result as array in D:\xampp2\htdocs\airtimez\referrals.php on line 80

Help me debug it

答:
$selected1['GEN1'] the $selected1 is a result object, not the fetched results, you fetch with $selected_levels.

To fetch multiple rows the fetch needs to be looped while($row = mysqli_fetch_array($selected1)).

You should not put variables into a SQL query, this will open you to SQL injections. Instead use parameterized queries.

If you only need the ids to get the sum just use a subquery.

Roughly:

```<code>$sel_referrals1="SELECT SUM(amount) as da_sum FROM topup WHERE user_id IN((SELECT t1.referree
                                        FROM referrals AS t1
                                        LEFT JOIN referrals AS t2 ON t2.referrer = t1.referree
                                        LEFT JOIN referrals AS t3 ON t3.referrer = t2.referree
                                        LEFT JOIN referrals AS t4 ON t4.referrer = t3.referree
                                        LEFT JOIN referrals AS t5 ON t5.referrer = t4.referree
                                        LEFT JOIN referrals AS t6 ON t6.referrer = t5.referree
                                        LEFT JOIN referrals AS t7 ON t7.referrer = t6.referree
                                        LEFT JOIN referrals AS t8 ON t8.referrer = t7.referree
                                        LEFT JOIN referrals AS t9 ON t9.referrer = t8.referree
                                        LEFT JOIN referrals AS t10 ON t10.referrer = t9.referree
                                        LEFT JOIN referrals AS t11 ON t11.referrer = t10.referree
                                        WHERE t1.referrer = ?))";
$selected1 = mysqli_prepare($conn, $sel_referrals1);
mysqli_stmt_bind_param($selected1, 'i', $_SESSION['user']);
mysqli_stmt_execute($selected1);
while($row = mysqli_stmt_fetch($selected1)){
     echo number_format($row['da_sum'], 2);
}
</code>```

Although you also might want to group the sums by userid.

Title: Use a range of values with a variable

Body:
I have the following queries;

$sel_referrals1="SELECT t1.referree AS GEN1, t2.referree as GEN2, t3.referree as GEN3, t4.referree as GEN4, t5.referree as GEN5, t6.referree as GEN6, t7.referree as GEN7, t8.referree as GEN8, t9.referree as GEN9, t10.referree as GEN10, t11.referree as GEN11
                                        FROM referrals AS t1
                                        LEFT JOIN referrals AS t2 ON t2.referrer = t1.referree
                                        LEFT JOIN referrals AS t3 ON t3.referrer = t2.referree
                                        LEFT JOIN referrals AS t4 ON t4.referrer = t3.referree
                                        LEFT JOIN referrals AS t5 ON t5.referrer = t4.referree
                                        LEFT JOIN referrals AS t6 ON t6.referrer = t5.referree
                                        LEFT JOIN referrals AS t7 ON t7.referrer = t6.referree
                                        LEFT JOIN referrals AS t8 ON t8.referrer = t7.referree
                                        LEFT JOIN referrals AS t9 ON t9.referrer = t8.referree
                                        LEFT JOIN referrals AS t10 ON t10.referrer = t9.referree
                                        LEFT JOIN referrals AS t11 ON t11.referrer = t10.referree
                                        WHERE t1.referrer = '{$_SESSION['user']}'";
$selected1 = mysqli_query($conn, $sel_referrals1);
$selected_levels= mysqli_fetch_array($selected1);

I wanted to process the results of the query as in the following statement;

$select_level1="SELECT SUM(amount) FROM topup WHERE user_id IN('{$selected1['GEN1']}')";//The is line 80
 $selected_level1 = mysqli_query($conn,$select_level1);
 $result_level1 = mysqli_fetch_row($selected_level1);
 $level1=number_format($result_level1[0],2);

However, i get the following error;

Fatal error: Cannot use object of type mysqli_result as array in D:\xampp2\htdocs\airtimez\referrals.php on line 80

Help me debug it

Body:
$selected1['GEN1'] the $selected1 is a result object, not the fetched results, you fetch with $selected_levels.

To fetch multiple rows the fetch needs to be looped while($row = mysqli_fetch_array($selected1)).

You should not put variables into a SQL query, this will open you to SQL injections. Instead use parameterized queries.

If you only need the ids to get the sum just use a subquery.

Roughly:

$sel_referrals1="SELECT SUM(amount) as da_sum FROM topup WHERE user_id IN((SELECT t1.referree
                                        FROM referrals AS t1
                                        LEFT JOIN referrals AS t2 ON t2.referrer = t1.referree
                                        LEFT JOIN referrals AS t3 ON t3.referrer = t2.referree
                                        LEFT JOIN referrals AS t4 ON t4.referrer = t3.referree
                                        LEFT JOIN referrals AS t5 ON t5.referrer = t4.referree
                                        LEFT JOIN referrals AS t6 ON t6.referrer = t5.referree
                                        LEFT JOIN referrals AS t7 ON t7.referrer = t6.referree
                                        LEFT JOIN referrals AS t8 ON t8.referrer = t7.referree
                                        LEFT JOIN referrals AS t9 ON t9.referrer = t8.referree
                                        LEFT JOIN referrals AS t10 ON t10.referrer = t9.referree
                                        LEFT JOIN referrals AS t11 ON t11.referrer = t10.referree
                                        WHERE t1.referrer = ?))";
$selected1 = mysqli_prepare($conn, $sel_referrals1);
mysqli_stmt_bind_param($selected1, 'i', $_SESSION['user']);
mysqli_stmt_execute($selected1);
while($row = mysqli_stmt_fetch($selected1)){
     echo number_format($row['da_sum'], 2);
}

Although you also might want to group the sums by userid.


问:
Is this kind of function calls permissible in C
```<code>char* p = init();
p = foo(p);        /* this one */
</code>```

the function foo prototype:

```<code>char* foo(char* p);
</code>```

Is it permissible to call foo that way, or does it fall in the Undefined Behavior category?

答:
Is it permissible to call foo that way, or does it fall in the Undefined Behavior category?

Yes it is, the order is guaranteed (a sequence point exists between the parameters' evaluation and the function call).

You are probably confusing that with side-effects of unsequenced modifications or something.

Body:
char* p = init();
p = foo(p);        /* this one */

the function foo prototype:

char* foo(char* p);

Is it permissible to call foo that way, or does it fall in the Undefined Behavior category?