问:
How to add a set of multiple values to a key?
I created a class which is basically a hobby book. The book can be accessed by two methods, enter(n,h) which takes a name and keep adding hobbies to that name(one name can have multiple hobbies). The other method returns a set of hobbies for a particular name. My hobby book is storing every hobby that I insert to one name. Can someone help me fixing it?

```<code>class Hobby:

    def __init__(self):
        self.dic={}
        self.hby=set()

    def enter(self,n,h):

        if n not in self.dic.items():
            self.dic[n]=self.hby
                for k in self.dic.items():
                    self.hby.add(h)

    def lookup(self,n):
        return self.dic[n]
</code>```

I tried running following cases

```<code>    d = Hobby(); d.enter('Roj', 'soccer'); d.lookup('Roj')
    {'soccer'}
    d.enter('Max', 'reading'); d.lookup('Max')
    {'reading', 'soccer'} #should return just reading
    d.enter('Roj', 'music'); d.lookup('Roj')
    {'reading', 'soccer','music'} #should return soccer and music
</code>```

答:
Why are you re-inventing a dict here? Why are you using a separate set to which you always add values, and reference it to every key which ensures that it always returns the same set on a lookup?

Don't reinvent the wheel, use collections.defaultdict:

```<code>import collections

d = collections.defaultdict(set)
d["Roj"].add("soccer")
d["Roj"]
# {'soccer'}
d["Max"].add("reading")
d["Max"]
# {'reading'}
d["Roj"].add("music")
d["Roj"]
# {'soccer', 'music'}
</code>```

.

UPDATE - If you really want to do it through your own class (and before you do, watch Stop Writing Classes!), you can do it as:

```<code>class Hobby(object):

    def __init__(self):
        self.container = {}

    def enter(self, n, h):
        if n not in self.container:
            self.container[n] = {h}
        else:
            self.container[n].add(h)

    def lookup(self, n):
        return self.container.get(n, None)

d = Hobby()
d.enter("Roj", "soccer")
d.lookup("Roj")
# {'soccer'}
d.enter("Max", "reading")
d.lookup("Max")
# {'reading'}
d.enter("Roj", "music")
d.lookup("Roj")
# {'soccer', 'music'}
</code>```

Note how no extra set is used here - every dict key gets its own set to populate.

Body:
I created a class which is basically a hobby book. The book can be accessed by two methods, enter(n,h) which takes a name and keep adding hobbies to that name(one name can have multiple hobbies). The other method returns a set of hobbies for a particular name. My hobby book is storing every hobby that I insert to one name. Can someone help me fixing it?

class Hobby:

    def __init__(self):
        self.dic={}
        self.hby=set()

    def enter(self,n,h):

        if n not in self.dic.items():
            self.dic[n]=self.hby
                for k in self.dic.items():
                    self.hby.add(h)

    def lookup(self,n):
        return self.dic[n]

I tried running following cases

    d = Hobby(); d.enter('Roj', 'soccer'); d.lookup('Roj')
    {'soccer'}
    d.enter('Max', 'reading'); d.lookup('Max')
    {'reading', 'soccer'} #should return just reading
    d.enter('Roj', 'music'); d.lookup('Roj')
    {'reading', 'soccer','music'} #should return soccer and music

Body:
Why are you re-inventing a dict here? Why are you using a separate set to which you always add values, and reference it to every key which ensures that it always returns the same set on a lookup?

Don't reinvent the wheel, use collections.defaultdict:

import collections

d = collections.defaultdict(set)
d["Roj"].add("soccer")
d["Roj"]
# {'soccer'}
d["Max"].add("reading")
d["Max"]
# {'reading'}
d["Roj"].add("music")
d["Roj"]
# {'soccer', 'music'}

.

UPDATE - If you really want to do it through your own class (and before you do, watch Stop Writing Classes!), you can do it as:

class Hobby(object):

    def __init__(self):
        self.container = {}

    def enter(self, n, h):
        if n not in self.container:
            self.container[n] = {h}
        else:
            self.container[n].add(h)

    def lookup(self, n):
        return self.container.get(n, None)

d = Hobby()
d.enter("Roj", "soccer")
d.lookup("Roj")
# {'soccer'}
d.enter("Max", "reading")
d.lookup("Max")
# {'reading'}
d.enter("Roj", "music")
d.lookup("Roj")
# {'soccer', 'music'}

Note how no extra set is used here - every dict key gets its own set to populate.


来源: stackexchange

问:
Partial Specialization of Operator()
One of my classes declares a templated function:

```<code>template<class A, class B>
A do_something(const std::vector<B> &data)
</code>```

which I'd like to partially specialize on typename A. B is a family of types that implement a pretty minimal interface, and we use a lot of them, so I'd like my specialization to be generic on B. I suspect this is doubly vexing as typename A is used only as the return type.

From the internet, I've gleaned that I can't partially specialize a function, so I've created a class as follows:

```<code>template<class A, class B>
class do_something_implementation {
  public:
    do_something_implementation(const std::vector<B> &data_) {
      data = data_;
    }

  int do_something_implementation<int, B>::operator()() {
    /* Complicated algorithm goes here... */
  }

  double do_something_implementation<double, B>::operator()() {
    /* Different complicated algorithm goes here... */
  }

  private:
      std::vector<B> data;
}
</code>```

When I try to compile that (using Visual Studio 2008), the compiler crashes (!) and I get the following error:

```<code>fatal error C1001: An internal error has occurred in the compiler.
</code>```

I assume this is my problem and not the compiler's. Is there a better way to express the partial specialization I'm aiming for?

答:
Usually, it goes like this:</p>

```<code>template <typename A, typename B>
struct DoSomethingHelper
{
    static A doIt(const std::vector<B> &data);
};

template <typename B>
struct DoSomethingHelper<double, B>
{
    static double doIt(const std::vector<B> &data) { ... }
};

template <typename B>
struct DoSomethingHelper<int, B>
{
    static int doIt(const std::vector<B> &data) { ... }
};

template<class A, class B>
A do_something(const std::vector<B> &data)
{ return DoSomethingHelper<A, B>::doIt(data); }
</code>```

ContentLicense: CC BY-SA 2.5

Title: Partial Specialization of Operator()

Body:
One of my classes declares a templated function:

template<class A, class B>
A do_something(const std::vector &data)

which I'd like to partially specialize on typename A. B is a family of types that implement a pretty minimal interface, and we use a lot of them, so I'd like my specialization to be generic on B. I suspect this is doubly vexing as typename A is used only as the return type.

From the internet, I've gleaned that I can't partially specialize a function, so I've created a class as follows:

template<class A, class B>
class do_something_implementation {
  public:
    do_something_implementation(const std::vector &data_) {
      data = data_;
    }

  int do_something_implementation<int, B>::operator()() {
    /* Complicated algorithm goes here... */
  }

  double do_something_implementation<double, B>::operator()() {
    /* Different complicated algorithm goes here... */
  }

  private:
      std::vector data;
}

When I try to compile that (using Visual Studio 2008), the compiler crashes (!) and I get the following error:

fatal error C1001: An internal error has occurred in the compiler.

I assume this is my problem and not the compiler's. Is there a better way to express the partial specialization I'm aiming for?

Body:
Usually, it goes like this:

template <typename A, typename B>
struct DoSomethingHelper
{
    static A doIt(const std::vector<B> &data);
};

template <typename B>
struct DoSomethingHelper<double, B>
{
    static double doIt(const std::vector<B> &data) { ... }
};

template <typename B>
struct DoSomethingHelper<int, B>
{
    static int doIt(const std::vector<B> &data) { ... }
};

template<class A, class B>
A do_something(const std::vector<B> &data)
{ return DoSomethingHelper<A, B>::doIt(data); }


问:
make Android Textview or EditText selectable
I want to make EditText or Textview selectable in my android project .
project is for android 4.0+ . I add this : txtView.setTextIsSelectable(true) and also : txtView.setCustomSelectionActionModeCallback(new myCallback());
to make my custom selection menu .
but this error happend when i want to select the text .

```<code>W/TextView﹕ TextView does not support text selection. Action mode cancelled.
</code>```

i searched about the error but didn't find the solution .what should i do ?

答:
setTextIsSelectable does fix the problem on Android 7.1.1 for sure. The setEnabled(false) and then true didn't work.

```<code>editText.setTextIsSelectable(true);
</code>```

My exact situation was having setFocusable(false) and adding an onClickListener, then setting setFocusable(true) and onClickListener(null) gave me the error in the OP.

(not correct syntax but you get the idea)

ContentLicense: CC BY-SA 3.0

Body:
I want to make EditText or Textview selectable in my android project .
project is for android 4.0+ . I add this : txtView.setTextIsSelectable(true) and also : txtView.setCustomSelectionActionModeCallback(new myCallback());
to make my custom selection menu .
but this error happend when i want to select the text .

W/TextView﹕ TextView does not support text selection. Action mode cancelled.

i searched about the error but didn't find the solution .what should i do ?

Body:
setTextIsSelectable does fix the problem on Android 7.1.1 for sure. The setEnabled(false) and then true didn't work.

editText.setTextIsSelectable(true);

My exact situation was having setFocusable(false) and adding an onClickListener, then setting setFocusable(true) and onClickListener(null) gave me the error in the OP.

(not correct syntax but you get the idea)


问:
Ansible web server role versioning strategy for several environments
we are currently starting to adopt ansible as our cm tool of choice across all our envs, we are looking into configuring an nginx server accross several dev, qa, uat and prod environments, we are looking into leveraging the templating module in order to enable ansible to deploy to each of these environments by using variables per env, what would be the best practice regarding the versioning strategy of the whole platform?

Should we have 1 branch for each env? so each env would have his variable file and each change to it would trigger a new version just for the env? or the best would be to have all the variables for all envs and a change would trigger a new version of everything? This assuming that we cannot have the same cofiguration for every env (yet),

Best Regards,

答:
You’s better use separate branches for each env so that an env can run against with others.

And using different branches can make it more traceable for a certain environment versions. It’s not the usual manners to update all environments at the same time (if your situation is update all environment at the same time, you can put all the variables together).


问:
YouTube Android Player API throws "BadParcelableException ClassNotFoundException when unmarshalling: asc" with new YouTube version
Filing bug to YouTube Android Player API Library engineers: see android-youtube-api tag

Over the course of the past week and a half, I've noticed this weird BadParcelableException steadily increasing in our app and have nailed it down to YouTube's new release on android.

This crash will occur if your app is playing a youtube video, bringing your app to background, force stopping the Youtube app, and resuming your app again. Crash reproducible on Youtube version 12.19.56. Also tested on an older YouTube version 12.05.21 and the crash was not there.

Stack trace:

```<code>main Exception: Unable to start activity ComponentInfo{com.myapp.MainActivity}:
android.os.BadParcelableException: ClassNotFoundException when unmarshalling: asc
Stack: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp.MainActivity}:
android.os.BadParcelableException: ClassNotFoundException when unmarshalling: asc
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2666)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2727)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1478)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6121)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779) Caused by:
android.os.BadParcelableException: ClassNotFoundException when unmarshalling: asc
at android.os.Parcel.readParcelableCreator(Parcel.java:2536)
at android.os.Parcel.readParcelable(Parcel.java:2462)
at android.os.Parcel.readValue(Parcel.java:2365)
at android.os.Parcel.readSparseArrayInternal(Parcel.java:2813)
at android.os.Parcel.readSparseArray(Parcel.java:2068)
at android.os.Parcel.readValue(Parcel.java:2422)
at android.os.Parcel.readArrayMapInternal(Parcel.java:2732)
at android.os.BaseBundle.unparcel(BaseBundle.java:269)
at android.os.Bundle.getSparseParcelableArray(Bundle.java:934)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1208)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at android.support.v4.app.FragmentManagerImpl.dispatchCreate(FragmentManager.java:2893)
at android.support.v4.app.FragmentController.dispatchCreate(FragmentController.java:190)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:353)
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:85)
at com.myapp.BaseActivity.onCreate(BaseActivity.java:36)
at com.myapp.MainActivity.onCreate(MainActivity.java:190)
at android.app.Activity.performCreate(Activity.java:6682)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2619) ... 9 more

Caused by: java.lang.ClassNotFoundException: Didn't find class "asc" on path: DexPathList[[zip file "/data/app/com.myapp-naA-_cCrz-w81rqx98ipcQ==/base.apk"],nativeLibraryDirectories=[/data/app/com.myapp-naA-_cCrz-w81rqx98ipcQ==/lib/arm64, /system/lib64, /vendor/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:93)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
... 32 more
</code>```

Some more info:

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    super.onCreate(savedInstanceState); // Crashing here MainActivity.java:190
    ...
}
</code>```

答:
Use following code in your onCreate:

```<code>@Override
public void onCreate(Bundle b) {
  if (b != null) {
    final ClassLoader contextCl = getClassLoader();
    b.setClassLoader(contextCl);
  }
  super.onCreate(b);
}
</code>```

The bug is probably due to YouTube library code storing custom Parcelable inside the state Bundle (YouTube library classes are probably obfuscated by Proguard, hence weird names like "asc").

If the suggestion above does not work, follow along the lines of @Fitz's suggestion and drop the state Bundle. Don't try to mess with it in onCreate (that won't work), instead it is best to override onSaveInstanceState to return Bundle.EMPTY if your app is suspended when you have a playback in progress.

Note, that the bug in question is pretty tricky in multiple ways. If you (or YouTube app) store nested Bundles inside each other, those also need to have proper ClassLoader set… Someone should tell Google to get some common sense and just use Thread#getContextClassLoader inside Bundle to fix that problem once and for all.

Body:
Filing bug to YouTube Android Player API Library engineers: see android-youtube-api tag

Over the course of the past week and a half, I've noticed this weird BadParcelableException steadily increasing in our app and have nailed it down to YouTube's new release on android.

This crash will occur if your app is playing a youtube video, bringing your app to background, force stopping the Youtube app, and resuming your app again. Crash reproducible on Youtube version 12.19.56. Also tested on an older YouTube version 12.05.21 and the crash was not there.

Stack trace:

main Exception: Unable to start activity ComponentInfo{com.myapp.MainActivity}:
android.os.BadParcelableException: ClassNotFoundException when unmarshalling: asc
Stack: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp.MainActivity}:
android.os.BadParcelableException: ClassNotFoundException when unmarshalling: asc
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2666)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2727)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1478)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6121)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779) Caused by:
android.os.BadParcelableException: ClassNotFoundException when unmarshalling: asc
at android.os.Parcel.readParcelableCreator(Parcel.java:2536)
at android.os.Parcel.readParcelable(Parcel.java:2462)
at android.os.Parcel.readValue(Parcel.java:2365)
at android.os.Parcel.readSparseArrayInternal(Parcel.java:2813)
at android.os.Parcel.readSparseArray(Parcel.java:2068)
at android.os.Parcel.readValue(Parcel.java:2422)
at android.os.Parcel.readArrayMapInternal(Parcel.java:2732)
at android.os.BaseBundle.unparcel(BaseBundle.java:269)
at android.os.Bundle.getSparseParcelableArray(Bundle.java:934)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1208)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at android.support.v4.app.FragmentManagerImpl.dispatchCreate(FragmentManager.java:2893)
at android.support.v4.app.FragmentController.dispatchCreate(FragmentController.java:190)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:353)
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:85)
at com.myapp.BaseActivity.onCreate(BaseActivity.java:36)
at com.myapp.MainActivity.onCreate(MainActivity.java:190)
at android.app.Activity.performCreate(Activity.java:6682)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2619) ... 9 more

Caused by: java.lang.ClassNotFoundException: Didn't find class "asc" on path: DexPathList[[zip file "/data/app/com.myapp-naA-_cCrz-w81rqx98ipcQ==/base.apk"],nativeLibraryDirectories=[/data/app/com.myapp-naA-_cCrz-w81rqx98ipcQ==/lib/arm64, /system/lib64, /vendor/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:93)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
... 32 more

Some more info:

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    super.onCreate(savedInstanceState); // Crashing here MainActivity.java:190
    ...
}

Body:
Use following code in your onCreate:

@Override
public void onCreate(Bundle b) {
  if (b != null) {
    final ClassLoader contextCl = getClassLoader();
    b.setClassLoader(contextCl);
  }
  super.onCreate(b);
}

The bug is probably due to YouTube library code storing custom Parcelable inside the state Bundle (YouTube library classes are probably obfuscated by Proguard, hence weird names like "asc").

If the suggestion above does not work, follow along the lines of @Fitz's suggestion and drop the state Bundle. Don't try to mess with it in onCreate (that won't work), instead it is best to override onSaveInstanceState to return Bundle.EMPTY if your app is suspended when you have a playback in progress.

Note, that the bug in question is pretty tricky in multiple ways. If you (or YouTube app) store nested Bundles inside each other, those also need to have proper ClassLoader set… Someone should tell Google to get some common sense and just use Thread#getContextClassLoader inside Bundle to fix that problem once and for all.


问:
Beginner Matlab function only plotting zero
I have been thrown in the deep end in one of my Signals classes. I am trying to learn Octave so that I can do the Matlab assignments required by the professor at home (I have not had any education in Matlab yet).

I have been reading as much as I can but I cannot seem to figure out why this function only seems to return 0. I think I am missing something fundamental but I don't know what.

```<code>t = [-1:0.1:5];

% (a): The Unit-step Function u(t)
function u = u (t)
    if(t >= 0)
        u = 1;
    else
        u = 0;
    end
end

plot(t, u(t));
</code>```

答:
The problem arises because the function enters a vector and returns a scalar, so plot draws erroneously.

One solution:

A possible solution is to create the new vector with zeros (), and then iterate with for by selecting the output with the if.

```<code>t = [-1:0.1:5];

% (a): The Unit-step Function u(t)
function u = u (t)
    u = zeros(size(t));
    for i=1:length(t)
        if(t(i) >= 0)
            u(i) = 1;
        else
            u(i) = 0;
        end
    end
end
plot(t, u(t));
</code>```

Second solution:

Another solution is to use the properties of matlab/octave to handle vector operations.

```<code>t = [-1:0.1:5];

% (a): The Unit-step Function u(t)
function u = u (t)
    u = t>=0
end
plot(t, u(t));
</code>```

Body:
I have been thrown in the deep end in one of my Signals classes. I am trying to learn Octave so that I can do the Matlab assignments required by the professor at home (I have not had any education in Matlab yet).

I have been reading as much as I can but I cannot seem to figure out why this function only seems to return 0. I think I am missing something fundamental but I don't know what.

t = [-1:0.1:5];

% (a): The Unit-step Function u(t)
function u = u (t)
    if(t >= 0)
        u = 1;
    else
        u = 0;
    end
end

plot(t, u(t));

Body:
The problem arises because the function enters a vector and returns a scalar, so plot draws erroneously.

One solution:

A possible solution is to create the new vector with zeros (), and then iterate with for by selecting the output with the if.

t = [-1:0.1:5];

% (a): The Unit-step Function u(t)
function u = u (t)
    u = zeros(size(t));
    for i=1:length(t)
        if(t(i) >= 0)
            u(i) = 1;
        else
            u(i) = 0;
        end
    end
end
plot(t, u(t));

Second solution:

Another solution is to use the properties of matlab/octave to handle vector operations.

t = [-1:0.1:5];

% (a): The Unit-step Function u(t)
function u = u (t)
    u = t>=0
end
plot(t, u(t));


问:
How do I change this so it fails the way I want?
I think the following code stops if it encounters any error, period.

```<code>public static void exportDatapointsToCSV(List<Datapoint> datapointList, File exportDir) {

    SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy (h:mm a)", Locale.US);
    File file = new File(exportDir, "my_datapoints.csv");

    try {
        file.createNewFile();
        CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
        csvWrite.writeNext(new String[]{"DATAPOINT_LABEL", "VALUE", "TIMESTAMP", "TIMESTAMP_FORMATTED", "NOTE"});

        for (Datapoint datapoint : datapointList) {
            String arrStr[] = new String[]{
                    datapoint.getLabel(),
                    datapoint.getValue() + "",
                    datapoint.getTimestamp() + "",
                    sdf.format(new Date(datapoint.getTimestamp())) + "",
                    datapoint.getNote()
            };
            csvWrite.writeNext(arrStr);
        }
        csvWrite.close();
    }
    catch (Exception sqlEx) {
        Log.e(LOG_TAG, sqlEx.getMessage(), sqlEx);
    }
}
</code>```

But I want it to:

Throw an error and stop if it can't create the file to begin with.

If it encounters an error on a given row, log it but move onto the next row, rather than stopping the entire thing.

Do I just move the try/catch into the loop? Does that cover it?

答:
The Exception that you are catching is the Grandfather of all Exceptions - If you look at the javadocs you will see that the constructor new FileWriter(file) throws a IOException

So if you wanted certain action e.g. logging and quitting if this failed then try

```<code> CSVWriter csvWrite = null;
 try {
         csvWrite = new CSVWriter(new FileWriter(file));
 } catch (IOException ex) {
    Log.e(LOG_TAG, ex.getMessage(), ex);
    return; // or System.exit or what either
 }
</code>```

Body:
I think the following code stops if it encounters any error, period.

public static void exportDatapointsToCSV(List<Datapoint> datapointList, File exportDir) {

    SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy (h:mm a)", Locale.US);
    File file = new File(exportDir, "my_datapoints.csv");

    try {
        file.createNewFile();
        CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
        csvWrite.writeNext(new String[]{"DATAPOINT_LABEL", "VALUE", "TIMESTAMP", "TIMESTAMP_FORMATTED", "NOTE"});

        for (Datapoint datapoint : datapointList) {
            String arrStr[] = new String[]{
                    datapoint.getLabel(),
                    datapoint.getValue() + "",
                    datapoint.getTimestamp() + "",
                    sdf.format(new Date(datapoint.getTimestamp())) + "",
                    datapoint.getNote()
            };
            csvWrite.writeNext(arrStr);
        }
        csvWrite.close();
    }
    catch (Exception sqlEx) {
        Log.e(LOG_TAG, sqlEx.getMessage(), sqlEx);
    }
}

But I want it to:

Throw an error and stop if it can't create the file to begin with.

If it encounters an error on a given row, log it but move onto the next row, rather than stopping the entire thing.

Do I just move the try/catch into the loop? Does that cover it?

Body:
The Exception that you are catching is the Grandfather of all Exceptions - If you look at the javadocs you will see that the constructor new FileWriter(file) throws a IOException

So if you wanted certain action e.g. logging and quitting if this failed then try

 CSVWriter csvWrite = null;
 try {
         csvWrite = new CSVWriter(new FileWriter(file));
 } catch (IOException ex) {
    Log.e(LOG_TAG, ex.getMessage(), ex);
    return; // or System.exit or what either
 }


问:
Is asynchronous call of JavaScript function possible in Windows Script Host?
Imagine you have a simple function in Windows Script Host (JScript) environment:

```<code>function say(text) {
    WScript.Sleep(5000);
    WScript.Echo(text);
}
</code>```

Is it possible to call say() asynchronously?

Note: Such browser-based methods as setInterval() or setTimeout are not available in WSH.

答: As far as I know, there is no equivalent to setTimeout / setInterval under Windows Script Host (shockingly). However, you may find this simple function queue in another answer here on SO a useful starting point for emulating it. Basically what the guy did (his name is also "TJ", but it's not me) was create a function queue, and then you call its main loop as your main method. The main loop emulates the heartbeat in browser-based implementations. Quite clever, though I'd change the naming a bit.

Body:
Imagine you have a simple function in Windows Script Host (JScript) environment:

function say(text) {
    WScript.Sleep(5000);
    WScript.Echo(text);
}

Is it possible to call say() asynchronously?

Note: Such browser-based methods as setInterval() or setTimeout are not available in WSH.


问:
Horizontally align table-cells within table
How can I horizontally align the text within this table-cell? It looks like it's floating to the right, and I'm not sure why.
https://jsfiddle.net/o06e11o9/

HTML

```<code><div class="affil2">
  <div class="oval2"></div>
  <div class="contents">
    a lorem ipsum dolor sit amet. Donec facilisis tortor ut augue lacinia, at viverra est semper. Sed sapien metus, tempor a tortor.
    <br />
    <br /> Pellentesque non dignissim neque. Ut porta viverra est, ut dignissim elit elementum ut.
  </div>
</div>
</code>```

CSS

```<code>.affil2 {
  align-content: center;
  display: table;
  text-align: center;
  z-index: 20;
  border: 1px solid #705A1D;
  position: relative;
  height: 200px;
  width: 960px;
  background-color: #af9254;
  box-shadow: 0px 3px 10px 0px rgba(0, 0, 0, .35);
}

.contents {
  margin: 0 auto;
  text-align: left;
  width: 600px;
  display: table-cell;
  vertical-align: middle;
  color: #fff;
  font-size: 18px;
}

.oval2 {
  z-index: 1;
  position: absolute;
  top: -110px;
  width: 1200px;
  height: 250px;
  border-radius: 100%;
  background: radial-gradient(ellipse at center, rgba(255, 255, 255, 0.3) 0%, rgba(255, 0, 0, 0) 100%);
}
</code>```

答:
CSS

```<code>.contents {
  padding-left: 200px;//hfhaunter
  padding-right: 200px;//hfhaunter
  margin: 0 auto;
  text-align: center;
  width: 100%;//thank you pablo cesar cordova morales
  display: table-cell;
  vertical-align: middle;
  color: #fff;
  font-size: 18px;
}
</code>```

Body:
How can I horizontally align the text within this table-cell? It looks like it's floating to the right, and I'm not sure why.
https://jsfiddle.net/o06e11o9/

HTML

    a lorem ipsum dolor sit amet. Donec facilisis tortor ut augue lacinia, at viverra est semper. Sed sapien metus, tempor a tortor.

 Pellentesque non dignissim neque. Ut porta viverra est, ut dignissim elit elementum ut.

CSS

.affil2 {
  align-content: center;
  display: table;
  text-align: center;
  z-index: 20;
  border: 1px solid #705A1D;
  position: relative;
  height: 200px;
  width: 960px;
  background-color: #af9254;
  box-shadow: 0px 3px 10px 0px rgba(0, 0, 0, .35);
}

.contents {
  margin: 0 auto;
  text-align: left;
  width: 600px;
  display: table-cell;
  vertical-align: middle;
  color: #fff;
  font-size: 18px;
}

.oval2 {
  z-index: 1;
  position: absolute;
  top: -110px;
  width: 1200px;
  height: 250px;
  border-radius: 100%;
  background: radial-gradient(ellipse at center, rgba(255, 255, 255, 0.3) 0%, rgba(255, 0, 0, 0) 100%);
}

Body:
CSS

.contents {
  padding-left: 200px;//hfhaunter
  padding-right: 200px;//hfhaunter
  margin: 0 auto;
  text-align: center;
  width: 100%;//thank you pablo cesar cordova morales
  display: table-cell;
  vertical-align: middle;
  color: #fff;
  font-size: 18px;
}


问:
How do I get Visual Studio Intellisense tooltips to show descriptions for .NET Framework 3.5?
I need to use .NET framework 3.5 for my project because it uses some older functionality.

The tooltips in Visual Studio aren't showing descriptions like they do when targeting a later framework. I just see basic information like method signatures and data types. Is there a way to fix this?

I looked for the xml files in C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v3.5 and it looks like it just has the files for the 3.5 Client Profile.

I tried reinstalling the 3.5 framework from this link: https://www.microsoft.com/en-us/download/details.aspx?id=21

I have no idea if it's working or not. When I run the executable nothing happens. I tried running as administrator. When I run it from command prompt there is no output.

I noticed the file is a hundred times smaller that the download for the latest .NET framework. Does that mean it doesn't include the files it's supposed to?

I'm guessing if there's a fix, it's either getting the correct xml files for .NET 3.5 or getting Visual Studio to use the xml files for .NET 4.6 even though my project is targeting 3.5.

Thanks in advance!

答:
You could try downloading the whole installer not just the bootloader installer.

.net 3.5 sp1

http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe

or if you dont want sp1

.net 3.5

http://download.microsoft.com/download/6/0/f/60fc5854-3cb8-4892-b6db-bd4f42510f28/dotnetfx35.exe

Edit

If you are unable to run the installer at all it sounds to me like it is already installed. You could try to verify the installation using this tool. This page also explains how to find the setup logs. It should shed some light on what is happening.


问:
How to get package name or applicationId in gradle build script?
I have moved from Ant script to gradle build script. But I don't know any way to get package name or applicationId in gradle build script.

答:
```<code>project.afterEvaluate {
    project.android.applicationVariants.all { variant ->
        def applicationId = [variant.mergedFlavor.applicationId, variant.buildType.applicationIdSuffix].findAll().join()
        ...
    }
}
</code>```

or define one in foo.gradle :

```<code>// foo.gradle
def appId = 'com.example.bar'
ext.appId = appId

// build.gradle
apply from: './foo.gradle'
...
defaultConfig {
   ...
   applicationId appId
}

// other.gradle you want
apply from: './foo.gradle'
...
task example {
    println(appId)
}
</code>```

Body:
project.afterEvaluate {
    project.android.applicationVariants.all { variant ->
        def applicationId = [variant.mergedFlavor.applicationId, variant.buildType.applicationIdSuffix].findAll().join()
        ...
    }
}

or define one in foo.gradle :

// foo.gradle
def appId = 'com.example.bar'
ext.appId = appId

// build.gradle
apply from: './foo.gradle'
...
defaultConfig {
   ...
   applicationId appId
}

// other.gradle you want
apply from: './foo.gradle'
...
task example {
    println(appId)
}


问:
How to set value for variable that refer to other class in constructor without parameter?
I have declared a list of variable including variable that refer to another class.

```<code>public class order {

    private int primaryid;
    private string desc;
    private int customerid;
    private Customer customer;

}
</code>```

And I already create the get and set methods. How can I assign value to variable customer in constructor without parameter?

```<code>public order(){
   primaryid = 0;
   desc = string.empty;
   customerid = 0;
   customer = ?
}
</code>```

答:
Other than setting customer to null or new Customer() then you can use one of two approaches:

Static variable:

```<code>void Main()
{
    order_helper.customer = new Customer();
    var order = new order();
}

public static class order_helper
{
    public static Customer customer;
}

public class order
{
    private int primaryid;
    private string desc;
    private int customerid;
    private Customer customer;

    public order()
    {
        primaryid = 0;
        desc = String.Empty;
        customerid = 0;
        customer = order_helper.customer;
    }
}
</code>```

Or reflection:

```<code>    var field =
        typeof(order)
            .GetField("customer", BindingFlags.Instance | BindingFlags.NonPublic);

    var order = new order();
    field.SetValue(order, new Customer());
</code>```

Body:
I have declared a list of variable including variable that refer to another class.

public class order {

    private int primaryid;
    private string desc;
    private int customerid;
    private Customer customer;

}

And I already create the get and set methods. How can I assign value to variable customer in constructor without parameter?

public order(){
   primaryid = 0;
   desc = string.empty;
   customerid = 0;
   customer = ?
}

Body:
Other than setting customer to null or new Customer() then you can use one of two approaches:

Static variable:

void Main()
{
    order_helper.customer = new Customer();
    var order = new order();
}

public static class order_helper
{
    public static Customer customer;
}

public class order
{
    private int primaryid;
    private string desc;
    private int customerid;
    private Customer customer;

    public order()
    {
        primaryid = 0;
        desc = String.Empty;
        customerid = 0;
        customer = order_helper.customer;
    }
}

Or reflection:

    var field =
        typeof(order)
            .GetField("customer", BindingFlags.Instance | BindingFlags.NonPublic);

    var order = new order();
    field.SetValue(order, new Customer());


问:
Ignore element appearance order in extension from base type
In an XSD, I have a ReturnType which is extended from base SaleType. I don't care about the order in which the elements appear in the xml.

I can change the XSD but I can't change the way the xml is written. For some reason the way xml is written is not in a sequential order as defined in the XSD. I could make the order not matter in base type but in the extension. How do I fix this?

```<code><xs:complexType name="SaleType">
    <xs:sequence>
        <xs:choice minOccurs="0" maxOccurs="unbounded"> <!--adding this ignores the order for Sale but does not enforce it to the extensions-->
            <xs:element name="ItemID" type="xs:string" />
            xs:element name="Description" type="xs:string" minOccurs="0"/>
        </xs:choice>
    </xs:sequence>
</xs:complexType>

<xs:complexType name="ReturnType">
    <xs:complexContent>
        <xs:extension base="SaleType">
            <xs:sequence>
                <xs:element name="Reason" type="xs:string" minOccurs="0"/>
            </xs:sequence>
        </xs:extension>
    </xs:complexContent>
</xs:complexType>

<!--Even though Description appears before ItemID, this xml validates since Reason is at the end-->
<Return>
    <Description>Item 123</Description>
    <ItemID>123</ItemID>
    <Reason>R1</Reason>
</Return>

<!--This xml does not validate since Reason is at the beginning-->
<Return>
    <Reason></Reason>
    <Description>Item 123</Description>
    <ItemID>123</ItemID>
</Return>
</code>```

答: You cannot use extension in XSD to override an order specified by a sequence.  See instead override if you cannot change the base class directly, but note that xs:override requires XSD 1.1.

Body:
In an XSD, I have a ReturnType which is extended from base SaleType. I don't care about the order in which the elements appear in the xml.

I can change the XSD but I can't change the way the xml is written. For some reason the way xml is written is not in a sequential order as defined in the XSD. I could make the order not matter in base type but in the extension. How do I fix this?

<xs:complexType name="SaleType">
    <xs:sequence>
        <xs:choice minOccurs="0" maxOccurs="unbounded">
            <xs:element name="ItemID" type="xs:string" />
            xs:element name="Description" type="xs:string" minOccurs="0"/>
        </xs:choice>
    </xs:sequence>
</xs:complexType>

<xs:complexType name="ReturnType">
    <xs:complexContent>
        <xs:extension base="SaleType">
            <xs:sequence>
                <xs:element name="Reason" type="xs:string" minOccurs="0"/>
            </xs:sequence>
        </xs:extension>
    </xs:complexContent>
</xs:complexType>

<Return>
    <Description>Item 123</Description>
    <ItemID>123</ItemID>
    <Reason>R1</Reason>
</Return>

<Return>
    <Reason></Reason>
    <Description>Item 123</Description>
    <ItemID>123</ItemID>
</Return>


问:
How can I capture all of the python log records generated during the execution of a series of Celery tasks?
I want to convert my homegrown task queue system into a Celery-based task queue, but one feature I currently have is causing me some distress.

Right now, my task queue operates very coarsely; I run the job (which generates data and uploads it to another server), collect the logging using a variant on Nose's log capture library, and then I store the logging for the task as a detailed result record in the application database.

I would like to break this down as three tasks:

collect data

upload data

report results (including all logging from the preceding two tasks)

The real kicker here is the logging collection. Right now, using the log capture, I have a series of log records for each log call made during the data generation and upload process. These are required for diagnostic purposes.  Given that the tasks are not even guaranteed to run in the same process, it's not clear how I would accomplish this in a Celery task queue.

My ideal solution to this problem will be a trivial and ideally minimally invasive method of capturing all logging during the predecessor tasks (1, 2) and making it available to the reporter task (3)

Am I best off remaining fairly coarse-grained with my task definition, and putting all of this work in one task? or is there a way to pass the existing captured logging around in order to collect it at the end?

答: It sounds like some kind of 'watcher' would be ideal. If you can watch and consume the logs as a stream you could slurp the results as they come in. Since the watcher would be running seperately and therefore have no dependencies with respect to what it is watching I believe this would satisfy your requirements for a non-invasive solution.</p>


问:
control servo using android
Asked question master, how to coding in arduino for controlling servo using android via bluetooth? Code below does not work, servo only runs between 48 - 56.</p>

```<code>#include <SoftwareSerial.h> #include <SoftwareSerial.h> #include <Servo.h> Servo servo; int bluetoothTx = 10; int bluetoothRx = 11; SoftwareSerial bluetooth(bluetoothTx, bluetoothRx); void setup() {   servo.attach(9);
 Serial.begin(9600); bluetooth.begin(9600);} void loop() {
//read from bluetooth and wrtite to usb serial
if(bluetooth.available()> 0 ){    int servopos = bluetooth.read();
Serial.println(servopos);
servo.write(servopos);}}
</code>```

答:
Read the data as string using: string input = bluetooth.readString();

Then convert string to int using: int servopos = int(input);

Then write the position to the servo:servo.write(servopos);

Now depending on the data you send from android, you could need to :

Trim it: input = input.trim();

Or constrain it : servopos = constrain(servopos,0,180);

Your corrected code:

```<code>#include <SoftwareSerial.h>
#include <Servo.h>
Servo servo;
int bluetoothTx = 10;
int bluetoothRx = 11;
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
void setup() {
  servo.attach(9);
  Serial.begin(9600);
  bluetooth.begin(9600);
}

void loop() {
  //read from bluetooth and wrtite to usb serial
  if (bluetooth.available() > 0 ) {
    String s = bluetooth.readString();
    s.trim();
    float servopos = s.toFloat();
    servopos = constrain(servopos, 0, 180);
    Serial.println("Angle: "+String(servopos));
    servo.write(servopos);
  }
}
</code>```

Title: control servo using android

Body:
Asked question master, how to coding in arduino for controlling servo using android via bluetooth? Code below does not work, servo only runs between 48 - 56.

#include <SoftwareSerial.h> #include <SoftwareSerial.h> #include <Servo.h> Servo servo; int bluetoothTx = 10; int bluetoothRx = 11; SoftwareSerial bluetooth(bluetoothTx, bluetoothRx); void setup() {   servo.attach(9);
 Serial.begin(9600); bluetooth.begin(9600);} void loop() {
//read from bluetooth and wrtite to usb serial
if(bluetooth.available()> 0 ){    int servopos = bluetooth.read();
Serial.println(servopos);
servo.write(servopos);}}

Body:
Read the data as string using: string input = bluetooth.readString();

Then convert string to int using: int servopos = int(input);

Then write the position to the servo:servo.write(servopos);

Now depending on the data you send from android, you could need to :

Trim it: input = input.trim();

Or constrain it : servopos = constrain(servopos,0,180);

Your corrected code:

#include <SoftwareSerial.h>
#include <Servo.h>
Servo servo;
int bluetoothTx = 10;
int bluetoothRx = 11;
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
void setup() {
  servo.attach(9);
  Serial.begin(9600);
  bluetooth.begin(9600);
}

void loop() {
  //read from bluetooth and wrtite to usb serial
  if (bluetooth.available() > 0 ) {
    String s = bluetooth.readString();
    s.trim();
    float servopos = s.toFloat();
    servopos = constrain(servopos, 0, 180);
    Serial.println("Angle: "+String(servopos));
    servo.write(servopos);
  }
}


问:
Form Application by using HTML
I want to create a HTML form . User will give input and the data will save in excel sheet.

Please support as soon as possible.

Thanks,
Joydeep Karmakar

答:
you will need to include Php with this form not HTML only because you should use PhpMyExcel to create that excel sheet and this site will help you to deal with PhpMyExcel functions PhpMyExcel-Documentation

and to create that HTML form you should try this tutorials W3schools

Title: Form Application by using HTML


问:
Hundred separator in Libre office calc number formating / Indian number formatting
I am moving to Open office spreadsheets and I need to handle large financial values in spread sheet cell.

By default libre office provide NUMBER & CURRENCY format, where "," is used as per Indian Numbering system(refer https://en.wikipedia.org/wiki/Indian_numbering_system )

However, I don't need the number till one's unit place. I need to see number in crore.

26,75,73,350 should be shown as 25.76

Libre office only provide "," as thousand separator. This separator follow US counting system, i.e. millons etc. If used as user-defined format "0.00,,"

I see cell value as 267.57 and not 26.76

What is a good user-defined format following Indian counting system?

答:
With a formula it would just be a matter of dividing by 10000000 (ten million) and showing decimal places to suit. Unfortunately Open Office Calc (like most other popular spreadsheet programs) does not provide such a format by default. However in a custom format , effectively divides by 1000 (one thousand) and % multiplies by 100 (one hundred) so 267573350 with a User-defined format of:

```<code> 0.00,,,%
</code>```

looks like 26.76%. The underlying value is however retained, so for example adding 1 to such a cell (in a different cell of general format) would show   267573351.

That is about as close as I can get just with formatting, but since % (ab)used this way is so open to confusion you might want to give some visual warning by say appending "C" to the format (0.00,,,%"C") to show:

```<code>  26.76%C
</code>```

Body:
With a formula it would just be a matter of dividing by 10000000 (ten million) and showing decimal places to suit. Unfortunately Open Office Calc (like most other popular spreadsheet programs) does not provide such a format by default. However in a custom format , effectively divides by 1000 (one thousand) and % multiplies by 100 (one hundred) so 267573350 with a User-defined format of:

 0.00,,,%

looks like 26.76%. The underlying value is however retained, so for example adding 1 to such a cell (in a different cell of general format) would show   267573351.

That is about as close as I can get just with formatting, but since % (ab)used this way is so open to confusion you might want to give some visual warning by say appending "C" to the format (0.00,,,%"C") to show:

  26.76%C


问:
Get the number of nodes in a variable-length relationship
Let's say I'm searching a books database with :CATEGORYs and :BOOKs.

I'm trying to find similar books to a current one written by a certain author. :BOOKs have :similar relationships to other books (the direction of the relationship is not relevant), and I would like to look for up to 3 similar chains. Here's my query:

```<code>MATCH (currentBook:BOOK {ISBN: {ISBN}})-[:similar*1..3]-(newBook:BOOK {author: {currentAuthor}})
RETURN newBook
</code>```

Here's the problem:

I need to find out how many similar relationships where used.

And by that, I mean how much the *1..3 actually meant for a specific book. So something like this:

```<code>MATCH (currentBook:BOOK {ISBN: {ISBN}})-[sim:similar*1..3]-(newBook:BOOK {author: {currentAuthor}})
SET newBook.simsUsed = AMOUNT_EXPANDED(sim)
RETURN newBook
</code>```

Here's a (fake) sample of my dataset.

答:
SIZE(sim) is probably what you are looking for.

For example, this query will return the length of each path:

```<code>MATCH (currentBook:BOOK {ISBN: "978-0446310789"})-[sim:similar*1..3]-(newBook:BOOK {author: "fake"})
RETURN currentBook, newBook, SIZE(sim) AS lth;
</code>```

You should NOT be setting newBook.simsUsed to that value, though, since the path length to any book depends on which book you started from, and the path length (starting from any particular book) might change over time. In general, you should avoid storing redundant data.

Body:
Let's say I'm searching a books database with :CATEGORYs and :BOOKs.

I'm trying to find similar books to a current one written by a certain author. :BOOKs have :similar relationships to other books (the direction of the relationship is not relevant), and I would like to look for up to 3 similar chains. Here's my query:

MATCH (currentBook:BOOK {ISBN: {ISBN}})-[:similar*1..3]-(newBook:BOOK {author: {currentAuthor}})
RETURN newBook

Here's the problem:

I need to find out how many similar relationships where used.

And by that, I mean how much the *1..3 actually meant for a specific book. So something like this:

MATCH (currentBook:BOOK {ISBN: {ISBN}})-[sim:similar*1..3]-(newBook:BOOK {author: {currentAuthor}})
SET newBook.simsUsed = AMOUNT_EXPANDED(sim)
RETURN newBook

Here's a (fake) sample of my dataset.

Body:
SIZE(sim) is probably what you are looking for.

For example, this query will return the length of each path:

MATCH (currentBook:BOOK {ISBN: "978-0446310789"})-[sim:similar*1..3]-(newBook:BOOK {author: "fake"})
RETURN currentBook, newBook, SIZE(sim) AS lth;

You should NOT be setting newBook.simsUsed to that value, though, since the path length to any book depends on which book you started from, and the path length (starting from any particular book) might change over time. In general, you should avoid storing redundant data.


问:
Typescript Error Cannot find name 'google' in ionic2 when using googlemaps javascript API
I am following Joshua Morony's Getting Started with Google Maps in Ionic 2 video tutorial.
I want to use google maps in my application and i end up with a typescript error. this is a part of the
pages/home/home.ts file

```<code>initMap(){
let latLng= new google.maps.LatLng(6.929848, 79.857407);

let mapOpt={
  center : latLng,
  zoom : 15,
  mapTypeId :google.maps.MapTypeId.ROADMAP
};

this.map= new google.maps.Map(this.mapElement.nativeElement,mapOpt);}
</code>```

I tried npm install --save @types/googlemaps,

but it still gives me the same typescript error Typescript Error
Cannot find name 'google'

答:
I solved it by installing:</p>

```<code>$npm install @types/googlemaps --save-dev
</code>```

Body:
I am following Joshua Morony's Getting Started with Google Maps in Ionic 2 video tutorial.
I want to use google maps in my application and i end up with a typescript error. this is a part of the
pages/home/home.ts file

initMap(){
let latLng= new google.maps.LatLng(6.929848, 79.857407);

let mapOpt={
  center : latLng,
  zoom : 15,
  mapTypeId :google.maps.MapTypeId.ROADMAP
};

this.map= new google.maps.Map(this.mapElement.nativeElement,mapOpt);}

I tried npm install --save @types/googlemaps,

but it still gives me the same typescript error Typescript Error
Cannot find name 'google'

Body:
I solved it by installing:

$npm install @types/googlemaps --save-dev


问:
Get past yearly gains in exploration in Amibroker
I am using Amibroker. I would like to get the yearly gain of last 2 years using AFL. The yearly gain is defined as price gain on last date of year in December compared to first date of year in January. One way to get this is to view the chart in yearly mode. However, I want the yearly returns to be obtained in AFL. </p>

答:
As you have no code to show, here's something to start.

```<code>b = TimeFrameGetPrice( "C", inYearly, -1 );
v = TimeFrameGetPrice( "C", inYearly, -2 );
change = ((b-v)/v)*100
printf("   = "+WriteVal(b)+"   = "+Writeval(v)+"  = "+WriteVal(change));
</code>```

This shows the rate of change for the past year if you put it unto Guru commentary.

You should be able to work out the previous year, then print the output to the chart and pretty it all up (with % symbol, different colors, etc). Look at TmeFrameCompress and Expand, to get data from different timeframes, PlotText function to plot output.

Body:
As you have no code to show, here's something to start.

b = TimeFrameGetPrice( "C", inYearly, -1 );
v = TimeFrameGetPrice( "C", inYearly, -2 );
change = ((b-v)/v)*100
printf("   = "+WriteVal(b)+"   = "+Writeval(v)+"  = "+WriteVal(change));

This shows the rate of change for the past year if you put it unto Guru commentary.

You should be able to work out the previous year, then print the output to the chart and pretty it all up (with % symbol, different colors, etc). Look at TmeFrameCompress and Expand, to get data from different timeframes, PlotText function to plot output.


问:
Laravel 5.4- How to receive JSON data from server and save in Database
I am using webservices. My requirement is to receive JSON data from server and store in DB[order table].Customers use to place mutliple Order in mobile.The same has to be received in laravel controller and stored in the order table.I should not use form only via controller I should receive data.
I am new to this concept of webservices and JSON.

```<code>public function receive(Request $request)
{
    $data = $request->json()->all();
    $order = new order();
    $order->product_int = $request->input('products');
    $order->quantity_float = $request->input('quantity');
    $order->amount_float = $request->input('amount');
    $order->save();
}
</code>```

In api.php , I am calling Route::get('/receive', 'OrderController@receive');
The above piece of code does not work.suggestions on how to receive JSON data as function parameter and how to save to DB.

答:
You should receive an associative array by using Input::all method in Laravel like below,

```<code>public function receive(Request $request)
{
   $data = Input::all(); //$data = $request->json()->all(); should also work
   $order = new order();
   $order->product_int = $data['products'];
   $order->quantity_float = $data['quantity'];
   $order->amount_float = $data['amount'];
   $order->save();
}
</code>```

And probably, you might want to change your route to have post instead of get,

```<code>Route::post('/receive', 'OrderController@receive');
</code>```

If you dont want a form to submit, then you can use CURL to post data to your API,

```<code>$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"YOUR-API-URL-HERE");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('products' => $value, 'quantity' => $quantity, 'amount' => $amount)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
curl_close ($ch);
</code>```

Body:
I am using webservices. My requirement is to receive JSON data from server and store in DB[order table].Customers use to place mutliple Order in mobile.The same has to be received in laravel controller and stored in the order table.I should not use form only via controller I should receive data.
I am new to this concept of webservices and JSON.

public function receive(Request $request)
{
    $data = $request->json()->all();
    $order = new order();
    $order->product_int = $request->input('products');
    $order->quantity_float = $request->input('quantity');
    $order->amount_float = $request->input('amount');
    $order->save();
}

In api.php , I am calling Route::get('/receive', 'OrderController@receive');
The above piece of code does not work.suggestions on how to receive JSON data as function parameter and how to save to DB.

Body:
You should receive an associative array by using Input::all method in Laravel like below,

public function receive(Request $request)
{
   $data = Input::all(); //$data = $request->json()->all(); should also work
   $order = new order();
   $order->product_int = $data['products'];
   $order->quantity_float = $data['quantity'];
   $order->amount_float = $data['amount'];
   $order->save();
}

And probably, you might want to change your route to have post instead of get,

Route::post('/receive', 'OrderController@receive');

If you dont want a form to submit, then you can use CURL to post data to your API,

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"YOUR-API-URL-HERE");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('products' => $value, 'quantity' => $quantity, 'amount' => $amount)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec ($ch);
curl_close ($ch);


问:
angularJs routeProvider issue
I have the below mentioned Angular code that uses the config and the routeProvider. View1 and View 2 are also enclosed.

```<code><!DOCTYPE html>
<html>
<head>
    <title>My test application</title>
</head>
<body ng-app="myApp">
    <div>
        <div ng-view></div>
    </div>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-
min.js"></script>
    <script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-
route.js"></script>
    <script>
        var myApp = angular.module('myApp', ['ngRoute']);

        myApp.config(function($routeProvider){
            $routeProvider
                .when('/',
                {
                    controller: 'SimpleController',
                    templateUrl: 'Partials/view1.html'
                })
                .when('/view2',{
                    controller: 'SimpleController'
                    templateUrl:'Partials/view2.html'
                })
                .otherwise({
                    redirectTo: '/'
                });
        });

        myApp.controller('SimpleController',SimpFunc);
        function SimpFunc($scope){
            $scope.customers = [
                {name:'Dave Smith', city:'New York'},
                {name:'Will Smith', city:'Phily'},
                {name:'Will Die', city:'Cincy'},
                {name:'Die till', city:'New Jersey'},
                {name:'Till What', city:'Cincy'}
            ];
            $scope.addCustomer = function(){
                $scope.customers.push(
                    {
                        name: $scope.newCust.name,
                        city: $scope.newCust.city
                    });
            };
        }
    </script>
</body>
</html>
</code>```

View1.html

```<code><div class="container">
<h2>View 1</h2>
Name:
<br />
<input type="text" ng-model="filter.name" />
<br />
<ul>
    <li ng-repeat="cust in customers | filter:filter.name">{{ cust.name
}} - {{ cust.city }}</li>
</ul>
<br />
Customer Name:
<br />
<input type="text" ng-model="newCust.name" />
Customer City:
<br />
<input type="text" ng-model="newCust.city" />
<br />
<button ng-click="addCustomer()">Add customer</button>
<br />
<a href="#/view2">View 2</a>
</div>
</code>```

View 2

```<code><div class="container">
<h2>View 2</h2>
City:
<br />
<input type="text" ng-model="filter.city" />
<br />
<ul>
    <li ng-repeat="cust in customers | filter:filter.city">{{ cust.name
}} - {{ cust.city }}</li>
</ul>
</div>
</code>```

I am not able to render view1 and/or view2 in the page. How can I do that?

答:
you have some syntax error in your app.config, also you have to make ng-href  instead href for example View 2, replace your codes with below codes.

also you miss define the controller in the Html

var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(function ($routeProvider) {
    $routeProvider.when('/',
        {
            controller: 'SimpleController',
            templateUrl: 'partials/view1.html'
        })
        .when('/view2',
        {
            controller: 'SimpleController',
            templateUrl: 'partials/view2.html'
        })
        .otherwise({
            redirectTo: '/'
        });
});

myApp.controller('SimpleController', function ($scope) {
    $scope.customers = [
        { name: 'Dave Smith', city: 'New York' },
        { name: 'Will Smith', city: 'Phily' },
        { name: 'Will Die', city: 'Cincy' },
        { name: 'Die till', city: 'New Jersey' },
        { name: 'Till What', city: 'Cincy' }
    ];

    $scope.addCustomer = function () {
        $scope.customers.push(
            {
                name: $scope.newCust.name,
                city: $scope.newCust.city
            });
    };
});
```
<pre class="lang-html prettyprint-override"><code><div ng-app="myApp" ng-controller="SimpleController">
  <div ng-view></div>
</div>
</code>```

Title: angularJs routeProvider issue

Body:
I have the below mentioned Angular code that uses the config and the routeProvider. View1 and View 2 are also enclosed.

<!DOCTYPE html>

    <title>My test application</title>

View1.html

View 1

Name:

<input type="text" ng-model="filter.name" />

{{ cust.name
}} - {{ cust.city }}

Customer Name:

<input type="text" ng-model="newCust.name" />
Customer City:

<input type="text" ng-model="newCust.city" />

<button ng-click="addCustomer()">Add customer</button>

View 2

View 2

View 2

City:

<input type="text" ng-model="filter.city" />

{{ cust.name
}} - {{ cust.city }}

I am not able to render view1 and/or view2 in the page. How can I do that?

Body:
you have some syntax error in your app.config, also you have to make ng-href  instead href for example <a ng-href="#!/view2">View 2</a>, replace your codes with below codes.

also you miss define the controller in the Html

var myApp = angular.module('myApp', ['ngRoute']);

myApp.config(function ($routeProvider) {
    $routeProvider.when('/',
        {
            controller: 'SimpleController',
            templateUrl: 'partials/view1.html'
        })
        .when('/view2',
        {
            controller: 'SimpleController',
            templateUrl: 'partials/view2.html'
        })
        .otherwise({
            redirectTo: '/'
        });
});

myApp.controller('SimpleController', function ($scope) {
    $scope.customers = [
        { name: 'Dave Smith', city: 'New York' },
        { name: 'Will Smith', city: 'Phily' },
        { name: 'Will Die', city: 'Cincy' },
        { name: 'Die till', city: 'New Jersey' },
        { name: 'Till What', city: 'Cincy' }
    ];

    $scope.addCustomer = function () {
        $scope.customers.push(
            {
                name: $scope.newCust.name,
                city: $scope.newCust.city
            });
    };
});

<div ng-app="myApp" ng-controller="SimpleController">
  <div ng-view></div>
</div>


问:
Best approach to determine Oracle INSERT or UPDATE using NiFi
I have a JSON flow-file and I need determine if I should be doing an INSERT or UPDATE. The trick is to only update the columns that match the JSON attributes. I have an ExecuteSQL working and it returns executesql.row.count, however I've lose the original JSON flow-file which I was planing to use as a routeonattribute. I'm trying to get the MergeContent to join the ExecuteSQL (dump the Avro output, I only need the executesql.row.count attribute) with the JSON flow. I've set follow before I do the ExecuteSQL:

fragment.count=2

fragment.identifier=${UUID()}

fragment.index=${nextInt()}

Alternatively I could create a MERGE, if there is a way to loop through the list of JSON attributes that match the Oracle table?

答:
How large is your JSON? If it's small, you might consider using ExtractText (matching the whole document) to get the JSON into an attribute. Then you can run ExecuteSQL, then ReplaceText to put the JSON back into the content (overwriting the Avro results). If your JSON is large, you could set up a DistributedMapCacheServer and (in a separate flow) run ExecuteSQL and store the value or executesql.row.count into the cache. Then in the JSON flow you can use FetchDistributedMapCache with the "Put Cache Value In Attribute" property set.

If you only need the JSON to use RouteOnAttribute, perhaps you could use EvaluateJsonPath before ExecuteSQL, so your conditions are already in attributes and you can replace the flow file contents.

If you want to use MergeContent, you can set fragment.count to 2, but rather than using the UUID() function, you could set "parent.identifier" to "${uuid}" using UpdateAttribute, then DuplicateFlowFile to create 2 copies, then UpdateAttribute to set "fragment.identifier" to "${parent.identifier}" and "fragment.index" to "${nextInt():mod(2)}". This gives a mergeable set of two flow files, you can route on fragment.index being 0 or 1, sending one to ExecuteSQL and one through the other flow, joining back up at MergeContent.

Another alternative is to use ConvertJSONToSQL set to "UPDATE", and if it fails, route those flow files to another ConvertJSONToSQL processor set to "INSERT".


问:
Get the value in the intermediate model in a Through Relationship
As I loop through a Prize.objects.all() set, I am trying to get the quantity value from PrizeItem, but it seems to reference only the GameItem model, not giving access to the intermediate PrizeItem attributes.

How do I get access to the Through model's attributes?

MODELS:

```<code>class GameItem(models.Model):
    '...'

class Prize(models.Model):
    '...'

    item            = models.ManyToManyField(GameItem, through='PrizeItem')

class PrizeItem(models.Model):
    #relations
    game_item        = models.ForeignKey(GameItem, on_delete=models.CASCADE)
    prize            = models.ForeignKey(Prize, on_delete=models.CASCADE)
    #Item details
    quantity         = models.IntegerField(null=True, blank=True, default=1)
</code>```

VIEWS:

```<code>def gameprizes(request):
    prizes=Prize.objects.all()
    context={'prizes':prizes}
    return render(request, "the-app/game-prizes.html", context)
</code>```

TEMPLATE:

```<code>{% if prize.item.all %}
<table class="table table-condensed">
    <tbody>
    {% for prize_item in prize.item.all %}
        <tr>
           <td>{{ prize_item.type }}</td><td>{{ prize_item.name }} {{ prize_item.quantity }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>
{% endif %}
</code>```

答:
What the hell with the models?
~> Use the @karthikr answer

Just prepare in views.py (overwrite query_set)

Use (_set ~ join) in html

Have a nice day, don't make it hard, give the hardest part for the strongest (server - database)

Body:
As I loop through a Prize.objects.all() set, I am trying to get the quantity value from PrizeItem, but it seems to reference only the GameItem model, not giving access to the intermediate PrizeItem attributes.

How do I get access to the Through model's attributes?

MODELS:

class GameItem(models.Model):
    '...'

class Prize(models.Model):
    '...'

    item            = models.ManyToManyField(GameItem, through='PrizeItem')

class PrizeItem(models.Model):
    #relations
    game_item        = models.ForeignKey(GameItem, on_delete=models.CASCADE)
    prize            = models.ForeignKey(Prize, on_delete=models.CASCADE)
    #Item details
    quantity         = models.IntegerField(null=True, blank=True, default=1)

VIEWS:

def gameprizes(request):
    prizes=Prize.objects.all()
    context={'prizes':prizes}
    return render(request, "the-app/game-prizes.html", context)

TEMPLATE:

{% if prize.item.all %}

    {% for prize_item in prize.item.all %}

           {{ prize_item.type }}	{{ prize_item.name }} {{ prize_item.quantity }}

    {% endfor %}

{% endif %}


问:
How to change JAVA.HOME for Eclipse/ANT
I am trying to sign a jar file using an ANT script. I know this has to be pointed at the JDK directory for jarsigner.exe to run, but when I echo java.home it returns the JRE directory.

This isn't a problem for javac, because I can set the executable path. But, that does not exist for signjar.

How do I change the java.home path? When I right-click on MyComputer and go to:

Properties > Advanced > Environment Variables

The "PATH" variable is correctly pointed to the JDK (C:\program files\java\jdk\bin).

Update: The file now signs correctly after changing the PATH variable suggested below.

答:
In Eclipse the Ant java.home variable is not based on the Windows JAVA_HOME environment variable.  Instead it is set to the home directory of the project's JRE.

To change the default JRE (e.g. change it to a JDK) you can go to Windows->Preferences... and choose Java->Installed JREs.

To change just a single project's JRE you can go to Project->Properties and choose Java Build Path and choose the Libraries tab.  Find the JRE System Library and click it, then choose Edit and choose the JRE (or JDK) that you want.

If that doesn't work then when running the build file you can choose Run as->Ant Build... and click the JRE tab, choose separate JRE and specify the JRE you want there.

Title: How to change JAVA.HOME for Eclipse/ANT


问:
Why can't I use JTAppleCalendar Pod File JTAppleCell in Swift 3?
I am using a JTAppleCalendar pod file in my project and when I installed the pod file I couldn't use the method JTAppleCell and I just could use JTAppleDayCell I watched this video
 https://www.youtube.com/watch?v=Qd_Gc67xzlw
and this
https://www.youtube.com/watch?v=zOphH-h-qCs
 Here is my codes </p>

```<code>import UIKit
import JTAppleCalendar

class calendarViewController: UIViewController {

@IBOutlet weak var calendarCollectionView: UICollectionView!

let formatter = DateFormatter()

override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

}

extension calendarViewController : JTAppleCalendarViewDataSource {

func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters {
    formatter.dateFormat = "yyyy MM dd"
    formatter.timeZone = Calendar.current.timeZone
    formatter.locale = Calendar.current.locale

    let startDate = formatter.date(from: "2017 01 01")!
    let endDate = formatter.date(from: "2017 12 31")!

    let parameters = ConfigurationParameters(startDate: startDate, endDate: endDate)
    return parameters
}

func calendar(_calebdar : JTAppleCalendarView , cellForItemAt date : Date , cellState : CellState , indexPath : IndexPath ) -> JTAppleDayCell {

    let cell = calendarCollectionView.dequeueReusableCell(withReuseIdentifier: "JTCustomCell", for: indexPath) as! JTCustomCell
    cell.dateLabel.text = cellState.text

    return cell
}

}
</code>```

答:
If you are only able to use JTAppleDayCell instead of JTAppleCell, then you are on the wrong version of the library. That video showed you for version 7.0

So the question I ask now is what version are you using?
put this in your podfile:

```<code>pod 'JTAppleCalendar'
</code>```

Then go to your console and run pod update.

The version should say 7.0.4 (which is the latest version as of this date).
If it is saying some other version, then you're doing something wrong.

ContentLicense: CC BY-SA 4.0

Body:
I am using a JTAppleCalendar pod file in my project and when I installed the pod file I couldn't use the method JTAppleCell and I just could use JTAppleDayCell I watched this video
 https://www.youtube.com/watch?v=Qd_Gc67xzlw
and this
https://www.youtube.com/watch?v=zOphH-h-qCs
 Here is my codes

import UIKit
import JTAppleCalendar

class calendarViewController: UIViewController {

@IBOutlet weak var calendarCollectionView: UICollectionView!

let formatter = DateFormatter()

override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

}

extension calendarViewController : JTAppleCalendarViewDataSource {

func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters {
    formatter.dateFormat = "yyyy MM dd"
    formatter.timeZone = Calendar.current.timeZone
    formatter.locale = Calendar.current.locale

    let startDate = formatter.date(from: "2017 01 01")!
    let endDate = formatter.date(from: "2017 12 31")!

    let parameters = ConfigurationParameters(startDate: startDate, endDate: endDate)
    return parameters
}

func calendar(_calebdar : JTAppleCalendarView , cellForItemAt date : Date , cellState : CellState , indexPath : IndexPath ) -> JTAppleDayCell {

    let cell = calendarCollectionView.dequeueReusableCell(withReuseIdentifier: "JTCustomCell", for: indexPath) as! JTCustomCell
    cell.dateLabel.text = cellState.text

    return cell
}

}

Body:
If you are only able to use JTAppleDayCell instead of JTAppleCell, then you are on the wrong version of the library. That video showed you for version 7.0

So the question I ask now is what version are you using?
put this in your podfile:

pod 'JTAppleCalendar'

Then go to your console and run pod update.

The version should say 7.0.4 (which is the latest version as of this date).
If it is saying some other version, then you're doing something wrong.


问:
spring data @query 'cached' table?
App entity

```<code>@Entity
@Table(name = "app")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class App implements Serializable {
    @ManyToMany
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    @JoinTable(name = "app_alloweduser",
               joinColumns = @JoinColumn(name="apps_id", referencedColumnName="id"),
               inverseJoinColumns = @JoinColumn(name="allowedusers_id", referencedColumnName="id"))
    private Set<User> allowedusers = new HashSet<>();
}
</code>```

I try to write my own query as such.

```<code>@Query("SELECT app FROM App app WHERE (:department is null or app.department = :department) and "
        + "(:platform is null or app.platform = :platform) and "
        + "(:appName is null or lower(app.appName) LIKE CONCAT('%',lower(:appName),'%')) and "
        + "(app.id in (SELECT b.apps_id FROM allowedusers b where b.allowedusers_id = :loginid))")
Page<App> findAllAllowed(@Param("department") Department department,
                         @Param("platform") Platform platform,
                         @Param("appName") String appName,
                         @Param("loginid") Long loginid,
                         Pageable pageable);
</code>```

Error: org.hibernate.hql.internal.ast.QuerySyntaxException: allowedusers is not mapped

I have tried app_alloweduser also and it too throws the same error that it can't map. The table APP_ALLOWEDUSER, which is what I am interested in is verified to be there though. So I am wondering what is going on here.

Some background
The table app_alloweduser has 2 column, app_id & user_id. I will first have to retrieve a list of app_id given a user_id. Then return all app from this list of app_id.

答:
I found out that I can access the table via a.allowedusers

Given the following declaration or particularly this line,

```<code>inverseJoinColumns = @JoinColumn(name="allowedusers_id", referencedColumnName="id"))
</code>```

I can access the database equivalent of app_alloweduser.allowedusers_id using a.allowedusers.id on JPQL.

```<code>@JoinTable(name = "app_alloweduser",
               joinColumns = @JoinColumn(name="apps_id", referencedColumnName="id"),
               inverseJoinColumns = @JoinColumn(name="allowedusers_id", referencedColumnName="id"))
    private Set<User> allowedusers = new HashSet<>();
</code>```

Final Query

```<code>@Query("SELECT a FROM App a JOIN a.allowedusers au WHERE au.id = :loginid AND "
            + "(:department is null or a.department = :department) AND "
            + "(:platform is null or a.platform = :platform) AND "
            + "(:appName is null or lower(a.appName) LIKE CONCAT('%',lower(:appName),'%'))")
Page<App> findAllAllowed(@Param("department") Department department,
                         @Param("platform") Platform platform,
                         @Param("appName") String appName,
                         @Param("loginid") Long loginid,
                         Pageable pageable);
</code>```

Title: spring data @query 'cached' table?

Body:
App entity

@Entity
@Table(name = "app")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class App implements Serializable {
    @ManyToMany
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    @JoinTable(name = "app_alloweduser",
               joinColumns = @JoinColumn(name="apps_id", referencedColumnName="id"),
               inverseJoinColumns = @JoinColumn(name="allowedusers_id", referencedColumnName="id"))
    private Set<User> allowedusers = new HashSet<>();
}

I try to write my own query as such.

@Query("SELECT app FROM App app WHERE (:department is null or app.department = :department) and "
        + "(:platform is null or app.platform = :platform) and "
        + "(:appName is null or lower(app.appName) LIKE CONCAT('%',lower(:appName),'%')) and "
        + "(app.id in (SELECT b.apps_id FROM allowedusers b where b.allowedusers_id = :loginid))")
Page<App> findAllAllowed(@Param("department") Department department,
                         @Param("platform") Platform platform,
                         @Param("appName") String appName,
                         @Param("loginid") Long loginid,
                         Pageable pageable);

Error: org.hibernate.hql.internal.ast.QuerySyntaxException: allowedusers is not mapped

I have tried app_alloweduser also and it too throws the same error that it can't map. The table APP_ALLOWEDUSER, which is what I am interested in is verified to be there though. So I am wondering what is going on here.

Some background
The table app_alloweduser has 2 column, app_id & user_id. I will first have to retrieve a list of app_id given a user_id. Then return all app from this list of app_id.

Body:
I found out that I can access the table via a.allowedusers

Given the following declaration or particularly this line,

inverseJoinColumns = @JoinColumn(name="allowedusers_id", referencedColumnName="id"))

I can access the database equivalent of app_alloweduser.allowedusers_id using a.allowedusers.id on JPQL.

@JoinTable(name = "app_alloweduser",
               joinColumns = @JoinColumn(name="apps_id", referencedColumnName="id"),
               inverseJoinColumns = @JoinColumn(name="allowedusers_id", referencedColumnName="id"))
    private Set<User> allowedusers = new HashSet<>();

Final Query

@Query("SELECT a FROM App a JOIN a.allowedusers au WHERE au.id = :loginid AND "
            + "(:department is null or a.department = :department) AND "
            + "(:platform is null or a.platform = :platform) AND "
            + "(:appName is null or lower(a.appName) LIKE CONCAT('%',lower(:appName),'%'))")
Page<App> findAllAllowed(@Param("department") Department department,
                         @Param("platform") Platform platform,
                         @Param("appName") String appName,
                         @Param("loginid") Long loginid,
                         Pageable pageable);


问:
MYSQL ORDER BY FIELD from a list from and other table
I'm scraching my head on this one for a long time and I don't know how to solve this.

I have 2 mysql tables

Table1

```<code>+----+----------------------+
| id | name    | order_list |
+----+----------------------+
|  1 | Bob     |    3       |
|  2 | Marc    |    2       |
|  3 | Edith   |    1       |
|  4 | John    |    4       |
+----+----------------------+
</code>```

Table2

```<code>+----+-------------------+
| id | user_id |  sale   |
+----+-------------------+
|  1 |   3     |   30    |
|  2 |   2     |   40    |
|  3 |   1     |   100   |
|  4 |   3     |   75    |
|  5 |   2     |   40    |
|  6 |   1     |   100   |
|  7 |   4     |   75    |
+----+-------------------+
</code>```

I need to have all purchase from table2 ORDER BY the order_list from table 1 of the user_id from table 2.

Right now I'm doing this in PHP like this.
1 query to get the id from employee from table 1 order by order_list.
A loop
Inside 1 query for each employee to get the sale

I need every sale independent, not sum or group by.

```<code>query to get the id from table 1 order by order_list
loop
    query the table2 for the sale of the looped employee
end loop
</code>```

I know that this can be done with something like this.

```<code>SELECT * FROM table2 ORDER BY FIELD (id,order from table 1)
</code>```

答:
```<code>SELECT a.* FROM table2 a
LEFT JOIN table1 b on a.user_id = b.id
ORDER BY b.order_list
</code>```

Just join them so you can access columns from the 2 tables.

Body:
I'm scraching my head on this one for a long time and I don't know how to solve this.

I have 2 mysql tables

Table1

+----+----------------------+
| id | name    | order_list |
+----+----------------------+
|  1 | Bob     |    3       |
|  2 | Marc    |    2       |
|  3 | Edith   |    1       |
|  4 | John    |    4       |
+----+----------------------+

Table2

+----+-------------------+
| id | user_id |  sale   |
+----+-------------------+
|  1 |   3     |   30    |
|  2 |   2     |   40    |
|  3 |   1     |   100   |
|  4 |   3     |   75    |
|  5 |   2     |   40    |
|  6 |   1     |   100   |
|  7 |   4     |   75    |
+----+-------------------+

I need to have all purchase from table2 ORDER BY the order_list from table 1 of the user_id from table 2.

Right now I'm doing this in PHP like this.
1 query to get the id from employee from table 1 order by order_list.
A loop
Inside 1 query for each employee to get the sale

I need every sale independent, not sum or group by.

query to get the id from table 1 order by order_list
loop
    query the table2 for the sale of the looped employee
end loop

I know that this can be done with something like this.

SELECT * FROM table2 ORDER BY FIELD (id,order from table 1)

Body:
SELECT a.* FROM table2 a
LEFT JOIN table1 b on a.user_id = b.id
ORDER BY b.order_list

Just join them so you can access columns from the 2 tables.


问:
How to add a column with values corresponding to another column?
I will summarize how I got the dataframes I work with:

```<code>     name abundance
1    joe  1
2    tim  1
3    bob  1
4    joe  1
5    bob  1
</code>```

First I created a new dataframe by aggregating the columns and calculated what the relative freqeuency would be:

```<code>     name  abundance  relative_ab
1    joe   2          0.4
2    tim   1          0.2
3    bob   2          0.4
</code>```

But I want to add a column to the first dataframe so that there are redundant entries with the relative_ab like so (the actual data set has other information in it and I would lose the information by aggregating them).

```<code>     name abundance relative_ab
1    joe  1         0.4
2    tim  1         0.2
3    bob  1         0.4
4    joe  1         0.4
5    bob  1         0.4
</code>```

I think I could brute force this but I am relatively new to R and wondering what slick ways you guys might come up with.

Thanks!

答:
We can do this with base R ave grouping by name and divide the group abundance sum by the complete abundance.

```<code>df$relative_ab <- with(df,ave(abundance, name, FUN = function(x)
                                        sum(x)/sum(abundance)))
df
#  name abundance relative_ab
#1  joe         1         0.4
#2  tim         1         0.2
#3  bob         1         0.4
#4  joe         1         0.4
#5  bob         1         0.4
</code>```

Body:
I will summarize how I got the dataframes I work with:

     name abundance
1    joe  1
2    tim  1
3    bob  1
4    joe  1
5    bob  1

First I created a new dataframe by aggregating the columns and calculated what the relative freqeuency would be:

     name  abundance  relative_ab
1    joe   2          0.4
2    tim   1          0.2
3    bob   2          0.4

But I want to add a column to the first dataframe so that there are redundant entries with the relative_ab like so (the actual data set has other information in it and I would lose the information by aggregating them).

     name abundance relative_ab
1    joe  1         0.4
2    tim  1         0.2
3    bob  1         0.4
4    joe  1         0.4
5    bob  1         0.4

I think I could brute force this but I am relatively new to R and wondering what slick ways you guys might come up with.

Thanks!

Body:
We can do this with base R ave grouping by name and divide the group abundance sum by the complete abundance.

df$relative_ab <- with(df,ave(abundance, name, FUN = function(x)
                                        sum(x)/sum(abundance)))
df
#  name abundance relative_ab
#1  joe         1         0.4
#2  tim         1         0.2
#3  bob         1         0.4
#4  joe         1         0.4
#5  bob         1         0.4


问:
Import directory text to create tree structure
I have several files that consist of folder path that looks like

```<code>//Fs1/userA/
//Fs1/userA/documents/
//Fs1/userB/
//Fs2/userC/documents
</code>```

I want to do analysis of which folders have x number direct sub folders. E.g. userD have 120 sub folders directly under it, not inclusive of deeper folders.

And I have huge collection of such files, some of them containing few hundred k rows.

I've thought of using radix tree, but it doesn't perform if I have to traverse down all its children to find the number of direct sub folders.

Also considered putting it into a database server to query, which might be easier to implement, but I wanted to try using .Net for analysis without sql servers. Any help?

答:
I took my xml project and removed xml.  Now I just get totals.  Maybe this will work for you.  The code checks folder and subfolder for all files and when size or number of files exceed a limit puts the results into the treeview. </p>

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace CheckFileSizes
{
    public partial class Form1 : Form
    {
        const int FILE_SIZE_CHECK = 10000000;
        const int FILE_COUNT_CHECK = 1000;
        public Form1()
        {
            InitializeComponent();

            folderBrowserDialog1.SelectedPath = @"c:\temp";
            textBoxTotalFolderSizeMin.Text = FILE_SIZE_CHECK.ToString();
            textBoxNumberOfFilesMin.Text = FILE_COUNT_CHECK.ToString();

        }
        private void buttonBrowseForFolder_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowDialog();
            textBoxFolderName.Text = folderBrowserDialog1.SelectedPath;
        }

        private void buttonMakeTree_Click(object sender, EventArgs e)
        {
            if (Directory.Exists(textBoxFolderName.Text))
            {
                MyDirectory root = MyDirectory.root;

                TreeNode rootNode = MakeTreeRecursive(textBoxFolderName.Text, root);
                textBoxTotalNumberOfFiles.Text = root.totalNumberOfFiles.ToString();
                textBoxTotalSize.Text = ((long)root.totalSize).ToString();

                if (rootNode == null)
                {
                    string rootNodeText = string.Format("Folder: '{0}', Number of Files: '{1}', File Size: '{2}'",
                        textBoxFolderName.Text,
                        textBoxTotalNumberOfFiles.Text,
                        textBoxTotalSize.Text
                    );
                    rootNode = new TreeNode(rootNodeText);
                }
                treeView1.Nodes.Add(rootNode);
                treeView1.ExpandAll();

            }
        }
        private TreeNode MakeTreeRecursive(string folder, MyDirectory myDirectory)
        {
            TreeNode node = null;

            myDirectory.name = folder.Substring(folder.LastIndexOf("\\") + 1);

            DirectoryInfo dInfo = new DirectoryInfo(folder);

            myDirectory.numberOfFiles = 0;
            myDirectory.size = 0.0f;

            foreach (FileInfo fInfo in dInfo.GetFiles())
            {
                try
                {
                    float fSize = fInfo.Length;
                    myDirectory.size += fSize;
                    myDirectory.numberOfFiles += 1;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error : CAnnot Access File '{0}'", fInfo.Name);
                }
            }
            myDirectory.totalSize = myDirectory.size;
            myDirectory.totalNumberOfFiles = myDirectory.numberOfFiles;
            foreach (string subFolder in Directory.GetDirectories(folder))
            {
                if (myDirectory.children == null) myDirectory.children = new List<MyDirectory>();
                MyDirectory childDirectory = new MyDirectory();
                myDirectory.children.Add(childDirectory);

                TreeNode childNode = MakeTreeRecursive(subFolder, childDirectory);
                if (childNode != null)
                {
                    if (node == null)
                    {
                        node = new TreeNode();
                    }
                    node.Nodes.Add(childNode);
                }

                myDirectory.totalSize += childDirectory.totalSize;
                myDirectory.totalNumberOfFiles += childDirectory.totalNumberOfFiles;
            }

            if ((myDirectory.totalNumberOfFiles >= long.Parse(textBoxNumberOfFilesMin.Text)) || myDirectory.totalSize >= float.Parse(textBoxTotalFolderSizeMin.Text))
            {
                if (node == null)
                {
                    node = new TreeNode();
                }
                string childNodeText = string.Format("Folder: '{0}', Number of Files: '{1}', File Size: '{2}'",
                    folder,
                    myDirectory.totalNumberOfFiles,
                    myDirectory.totalSize
                );
                node.Text =  childNodeText;
            }
            return node;
        }

    }
    public class MyDirectory
    {
        public static MyDirectory root = new MyDirectory();
        public List<MyDirectory> children { get; set; }

        public string name { get; set; }
        public long totalNumberOfFiles = 0;
        public int numberOfFiles = 0;
        public float size = 0.0f;
        public float totalSize = 0.0f;
    }
}
</code>```

Body:
I have several files that consist of folder path that looks like

//Fs1/userA/
//Fs1/userA/documents/
//Fs1/userB/
//Fs2/userC/documents

I want to do analysis of which folders have x number direct sub folders. E.g. userD have 120 sub folders directly under it, not inclusive of deeper folders.

And I have huge collection of such files, some of them containing few hundred k rows.

I've thought of using radix tree, but it doesn't perform if I have to traverse down all its children to find the number of direct sub folders.

Also considered putting it into a database server to query, which might be easier to implement, but I wanted to try using .Net for analysis without sql servers. Any help?

Body:
I took my xml project and removed xml.  Now I just get totals.  Maybe this will work for you.  The code checks folder and subfolder for all files and when size or number of files exceed a limit puts the results into the treeview.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace CheckFileSizes
{
    public partial class Form1 : Form
    {
        const int FILE_SIZE_CHECK = 10000000;
        const int FILE_COUNT_CHECK = 1000;
        public Form1()
        {
            InitializeComponent();

            folderBrowserDialog1.SelectedPath = @"c:\temp";
            textBoxTotalFolderSizeMin.Text = FILE_SIZE_CHECK.ToString();
            textBoxNumberOfFilesMin.Text = FILE_COUNT_CHECK.ToString();

        }
        private void buttonBrowseForFolder_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowDialog();
            textBoxFolderName.Text = folderBrowserDialog1.SelectedPath;
        }

        private void buttonMakeTree_Click(object sender, EventArgs e)
        {
            if (Directory.Exists(textBoxFolderName.Text))
            {
                MyDirectory root = MyDirectory.root;

                TreeNode rootNode = MakeTreeRecursive(textBoxFolderName.Text, root);
                textBoxTotalNumberOfFiles.Text = root.totalNumberOfFiles.ToString();
                textBoxTotalSize.Text = ((long)root.totalSize).ToString();

                if (rootNode == null)
                {
                    string rootNodeText = string.Format("Folder: '{0}', Number of Files: '{1}', File Size: '{2}'",
                        textBoxFolderName.Text,
                        textBoxTotalNumberOfFiles.Text,
                        textBoxTotalSize.Text
                    );
                    rootNode = new TreeNode(rootNodeText);
                }
                treeView1.Nodes.Add(rootNode);
                treeView1.ExpandAll();

            }
        }
        private TreeNode MakeTreeRecursive(string folder, MyDirectory myDirectory)
        {
            TreeNode node = null;

            myDirectory.name = folder.Substring(folder.LastIndexOf("\\") + 1);

            DirectoryInfo dInfo = new DirectoryInfo(folder);

            myDirectory.numberOfFiles = 0;
            myDirectory.size = 0.0f;

            foreach (FileInfo fInfo in dInfo.GetFiles())
            {
                try
                {
                    float fSize = fInfo.Length;
                    myDirectory.size += fSize;
                    myDirectory.numberOfFiles += 1;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error : CAnnot Access File '{0}'", fInfo.Name);
                }
            }
            myDirectory.totalSize = myDirectory.size;
            myDirectory.totalNumberOfFiles = myDirectory.numberOfFiles;
            foreach (string subFolder in Directory.GetDirectories(folder))
            {
                if (myDirectory.children == null) myDirectory.children = new List<MyDirectory>();
                MyDirectory childDirectory = new MyDirectory();
                myDirectory.children.Add(childDirectory);

                TreeNode childNode = MakeTreeRecursive(subFolder, childDirectory);
                if (childNode != null)
                {
                    if (node == null)
                    {
                        node = new TreeNode();
                    }
                    node.Nodes.Add(childNode);
                }

                myDirectory.totalSize += childDirectory.totalSize;
                myDirectory.totalNumberOfFiles += childDirectory.totalNumberOfFiles;
            }

            if ((myDirectory.totalNumberOfFiles >= long.Parse(textBoxNumberOfFilesMin.Text)) || myDirectory.totalSize >= float.Parse(textBoxTotalFolderSizeMin.Text))
            {
                if (node == null)
                {
                    node = new TreeNode();
                }
                string childNodeText = string.Format("Folder: '{0}', Number of Files: '{1}', File Size: '{2}'",
                    folder,
                    myDirectory.totalNumberOfFiles,
                    myDirectory.totalSize
                );
                node.Text =  childNodeText;
            }
            return node;
        }

    }
    public class MyDirectory
    {
        public static MyDirectory root = new MyDirectory();
        public List<MyDirectory> children { get; set; }

        public string name { get; set; }
        public long totalNumberOfFiles = 0;
        public int numberOfFiles = 0;
        public float size = 0.0f;
        public float totalSize = 0.0f;
    }
}