问:
How to group foreach statement by id in c#
I'm having a little challenge, and I am pretty new to mvc. My question is,

How do i group a bunch of foreach statements, by the id of the table it is being called from. here is my code:

```<code>foreach (
                        var owner in
                            _entities.LLAttrDatas.Where(
                                n => n.AttrID == 2 && n.ValStr.Contains(searchInputModel.OwnersName)))
                    {
                        ViewBag.searchName = owner.ValStr;
                    }

                    foreach (
                        var ownerAddress in
                            _entities.LLAttrDatas.Where(
                                n => n.AttrID == 3 && n.ValStr.Contains(searchInputModel.OwnersAddress)))
                    {
                        ViewBag.searchAddress = ownerAddress.ValStr;
                    }

                    foreach (
                        var propertyAddress in
                            _entities.LLAttrDatas.Where(
                                n => n.AttrID == 4 && n.ValStr.Contains(searchInputModel.DescriptionOrLocationOfProp)))
                    {
                        ViewBag.searchProperty = propertyAddress.ValStr;
                    }

                    foreach (
                        var propertyVolumeNo in
                            _entities.LLAttrDatas.Where(
                                n => n.AttrID == 5 && n.ValStr.Contains(searchInputModel.VolumeNumber)))
                    {
                        ViewBag.searchPropertyVolumeNo = propertyVolumeNo.ValStr;
                    }

                    foreach (
                        var propertyPlanNo in
                            _entities.LLAttrDatas.Where(
                                n => n.AttrID == 6 && n.ValStr.Contains(searchInputModel.SurveyPlanNumber))
                        )
                    {
                        ViewBag.searchPropertyPlanNo = propertyPlanNo.ValStr;
                    }
</code>```

Right now, when a user makes a search against any of the above query, just one result is being shown. I want it to display all the results from the different queries since they all have the same ID. Any help will be highly appreciated thanks.

Thanks y'all for your comments and support. We learn everyday. Anyways, I found a better way of doing it:

```<code>public IQueryable<DocumentProperty> GetDocuments(DocumentSearchInputModel searchInputModel)
            {
                Context = new DataContext();

                if (Context != null)
                {
                    var result = Context.DocumentsForSearch.AsQueryable();
                    if (searchInputModel != null)
                    {

                        result =
                            Context.DocumentsForSearch.Where(
                                d =>
                                    d.DescriptionOrLocationOfProp.Contains(searchInputModel.DescriptionOrLocationOfProp)
                                    || d.OwnersAddress.Contains(searchInputModel.OwnersAddress)
                                    || d.OwnersName.Contains(searchInputModel.OwnersName)
                                    || d.SurveyPlanNumber.Contains(searchInputModel.SurveyPlanNumber)
                                    || d.VolumeNumber.Contains(searchInputModel.VolumeNumber)
                                    || d.FileUrl.Contains(searchInputModel.OwnersName));

                    }
                    Logger.Info($"Results found {result}");
                    return result;
                }
                return null;
            }
</code>```

Now the only issue i'm having is how to display the search result in the view. how do i do a foreach where AttrID and ValStr match, and if the user search in only one field (because its a multi search system), I want the result to display all the fields with the same ID (i.e d.ID). Thanks.

答:
Your AttrID is obviously alias for properties in your search model. Define the alias table properly and you will improve readability and speed of generated request:</p>

```<code>        var forwardMap = new Dictionary<int, string>()
                       {
                           {2, searchInputModel.OwnersName},
                           {3, searchInputModel.OwnersAddress},
                           {4, searchInputModel.DescriptionOrLocationOfProp},
                           {5, searchInputModel.VolumeNumber},
                           {6, searchInputModel.SurveyPlanNumber},
                       };

        //common request for all your properties. You can wrap it into function.
        var query = _entities.LLAttrDatas
                             .GroupBy(x => x.AttrID)
                             .Where(x => forwardMap.Keys.Contains(x.Key))
                             .Select(x => new
                                          {
                                              id = x.Key,
                                              val = x.FirstOrDefault(y => y.ValStr.Contains(forwardMap[x.Key]))
                                          });

        //request to server
        var result = query.ToDictionary(x => x.id, x => x.val);

        //now result contains corresponding values (don't forget to check them for existance, if they are not present in table, they will not be present in result and throw exception)
        ViewBag.searchName = result[2];
        ViewBag.searchAddress = result[3];
        ViewBag.searchProperty = result[4];
        ViewBag.searchPropertyVolumeNo = result[5];
        ViewBag.searchPropertyPlanNo = result[6];
</code>```

Body:
I'm having a little challenge, and I am pretty new to mvc. My question is,

How do i group a bunch of foreach statements, by the id of the table it is being called from. here is my code:

foreach (
                        var owner in
                            _entities.LLAttrDatas.Where(
                                n => n.AttrID == 2 && n.ValStr.Contains(searchInputModel.OwnersName)))
                    {
                        ViewBag.searchName = owner.ValStr;
                    }

                    foreach (
                        var ownerAddress in
                            _entities.LLAttrDatas.Where(
                                n => n.AttrID == 3 && n.ValStr.Contains(searchInputModel.OwnersAddress)))
                    {
                        ViewBag.searchAddress = ownerAddress.ValStr;
                    }

                    foreach (
                        var propertyAddress in
                            _entities.LLAttrDatas.Where(
                                n => n.AttrID == 4 && n.ValStr.Contains(searchInputModel.DescriptionOrLocationOfProp)))
                    {
                        ViewBag.searchProperty = propertyAddress.ValStr;
                    }

                    foreach (
                        var propertyVolumeNo in
                            _entities.LLAttrDatas.Where(
                                n => n.AttrID == 5 && n.ValStr.Contains(searchInputModel.VolumeNumber)))
                    {
                        ViewBag.searchPropertyVolumeNo = propertyVolumeNo.ValStr;
                    }

                    foreach (
                        var propertyPlanNo in
                            _entities.LLAttrDatas.Where(
                                n => n.AttrID == 6 && n.ValStr.Contains(searchInputModel.SurveyPlanNumber))
                        )
                    {
                        ViewBag.searchPropertyPlanNo = propertyPlanNo.ValStr;
                    }

Right now, when a user makes a search against any of the above query, just one result is being shown. I want it to display all the results from the different queries since they all have the same ID. Any help will be highly appreciated thanks.

Thanks y'all for your comments and support. We learn everyday. Anyways, I found a better way of doing it:

public IQueryable<DocumentProperty> GetDocuments(DocumentSearchInputModel searchInputModel)
            {
                Context = new DataContext();

                if (Context != null)
                {
                    var result = Context.DocumentsForSearch.AsQueryable();
                    if (searchInputModel != null)
                    {

                        result =
                            Context.DocumentsForSearch.Where(
                                d =>
                                    d.DescriptionOrLocationOfProp.Contains(searchInputModel.DescriptionOrLocationOfProp)
                                    || d.OwnersAddress.Contains(searchInputModel.OwnersAddress)
                                    || d.OwnersName.Contains(searchInputModel.OwnersName)
                                    || d.SurveyPlanNumber.Contains(searchInputModel.SurveyPlanNumber)
                                    || d.VolumeNumber.Contains(searchInputModel.VolumeNumber)
                                    || d.FileUrl.Contains(searchInputModel.OwnersName));

                    }
                    Logger.Info($"Results found {result}");
                    return result;
                }
                return null;
            }

Now the only issue i'm having is how to display the search result in the view. how do i do a foreach where AttrID and ValStr match, and if the user search in only one field (because its a multi search system), I want the result to display all the fields with the same ID (i.e d.ID). Thanks.

Body:
Your AttrID is obviously alias for properties in your search model. Define the alias table properly and you will improve readability and speed of generated request:

        var forwardMap = new Dictionary<int, string>()
                       {
                           {2, searchInputModel.OwnersName},
                           {3, searchInputModel.OwnersAddress},
                           {4, searchInputModel.DescriptionOrLocationOfProp},
                           {5, searchInputModel.VolumeNumber},
                           {6, searchInputModel.SurveyPlanNumber},
                       };

        //common request for all your properties. You can wrap it into function.
        var query = _entities.LLAttrDatas
                             .GroupBy(x => x.AttrID)
                             .Where(x => forwardMap.Keys.Contains(x.Key))
                             .Select(x => new
                                          {
                                              id = x.Key,
                                              val = x.FirstOrDefault(y => y.ValStr.Contains(forwardMap[x.Key]))
                                          });

        //request to server
        var result = query.ToDictionary(x => x.id, x => x.val);

        //now result contains corresponding values (don't forget to check them for existance, if they are not present in table, they will not be present in result and throw exception)
        ViewBag.searchName = result[2];
        ViewBag.searchAddress = result[3];
        ViewBag.searchProperty = result[4];
        ViewBag.searchPropertyVolumeNo = result[5];
        ViewBag.searchPropertyPlanNo = result[6];


来源: stackexchange

问:
How to execute main1 when I have main1, main2, and main?
```<code>#include <stdio.h>
#include <string.h>

int main1(void)
{
   printf("Came to main1.\n");
}

int main2(void)
{
   printf("Came to main2.\n");
}

int main(void)
{
   printf("Came to main. \n");
}
</code>```

I have main1, main2, and main. I want to see main1 output, but every time I execute the program, I can only see main output

答:
That's because main() is always the entry point for a C/C++ program and is the only implicitly called function.

Try:

```<code>int main(void) {
   printf("Came to main. \n");
   main1();
   main2();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
#include <stdio.h>
#include <string.h>

int main1(void)
{
   printf("Came to main1.\n");
}

int main2(void)
{
   printf("Came to main2.\n");
}

int main(void)
{
   printf("Came to main. \n");
}

I have main1, main2, and main. I want to see main1 output, but every time I execute the program, I can only see main output

Body:
That's because main() is always the entry point for a C/C++ program and is the only implicitly called function.

Try:

int main(void) {
   printf("Came to main. \n");
   main1();
   main2();
}


问:
HTML - CSS: Styling <object>?
If my div container has this:

```<code><div id="container"><img src...
</code>```

I can style the image by this:

```<code>CSS
#container img{ ... }
</code>```

For object tag

```<code><div id="container"><object ...
</code>```

How do I address it? I tried this:

```<code>CSS
#container object{ width: 100px; }
</code>```

But it does not work.

Assume the I cant define "id" or "class" for the object tag

I am using tinymce to embed to youtube video. And the code will be rendered like this:

```<code><div id="container">
...

    <div id="content">
      <p>
      <object width="435" height="350" type="application/x-shockwave-flash" data="http://www.youtube.com/v/l9caxMr9RgY">
      <param value="http://www.youtube.com/v/XXXXXX" name="src"></object>
      </p>
    </div>
</div>
</code>```

答: You can assign an id or class for the object tat, that is perfectly correct. If you want the object to adapt to the width of its parent, just set its width to 100%. If you are using the <object> to embed flash, set the width for the <embed> tag also.

ContentLicense: CC BY-SA 2.5

Title: HTML - CSS: Styling <object>?

Body:
If my div container has this:

<img src...

I can style the image by this:

CSS
#container img{ ... }

For object tag

<object ...

How do I address it? I tried this:

CSS
#container object{ width: 100px; }

But it does not work.

Assume the I cant define "id" or "class" for the object tag

I am using tinymce to embed to youtube video. And the code will be rendered like this:

...

      <object width="435" height="350" type="application/x-shockwave-flash" data="http://www.youtube.com/v/l9caxMr9RgY">
      <param value="http://www.youtube.com/v/XXXXXX" name="src"></object>


问:
Flow: How do I type-annotate a local/global variable?
If I have the process.browser variable in my code how can I annotate it?</p>

答:
You can declare the process variable:

// @flow

declare var process: { browser: number }

const foo = process.browser * 3
```

<p>Here is a sample of it in action: https://flow.org/try/#0PTAEAEDMBsHsHcBQiAmBTAxtAhgJzaAG56gAOusGaAztQFygDeoARhfNWrgwHYCuAWxZdQAX2QZYPagBdQkWLFABeMhSq0AdGwSdcoAFSgAzIiA</p>

<p>In this example the global variable is declared locally in the file that consumes it, however it might be more ideal to declare this globally via a library definition. Going this route, it will automatically be defined for every file.</p>

<p>For example, add the following to <code><PROJECT_ROOT>/flow-typed/process.js</code> and you should be set. You may need to restart the Flow server.</p>

<pre class="lang-js prettyprint-override"><code>declare var process: { browser: number }
</code>```

Body:
You can declare the process variable:

// @flow

declare var process: { browser: number }

const foo = process.browser * 3

Here is a sample of it in action: https://flow.org/try/#0PTAEAEDMBsHsHcBQiAmBTAxtAhgJzaAG56gAOusGaAztQFygDeoARhfNWrgwHYCuAWxZdQAX2QZYPagBdQkWLFABeMhSq0AdGwSdcoAFSgAzIiA

In this example the global variable is declared locally in the file that consumes it, however it might be more ideal to declare this globally via a library definition. Going this route, it will automatically be defined for every file.

For example, add the following to <PROJECT_ROOT>/flow-typed/process.js and you should be set. You may need to restart the Flow server.

declare var process: { browser: number }


问:
pyspark convert transactions into a list of list
I want to use PrefixSpan sequence mining in pyspark. The format of data that I need to have is the following:

```<code>[[['a', 'b'], ['c']],  [['a'], ['c', 'b'], ['a', 'b']],  [['a', 'b'], ['e']], [['f']]]
</code>```

where the innermost elements are productIds, then there are orders (containing list of products) and then there are clients (containing lists of orders).

My data has transactional format:

```<code>clientId orderId product
</code>```

where orderId has multiple rows for separate products and clientId has multiple rows for separate orders.

Sample data:

```<code>test = sc.parallelize([[u'1', u'100', u'a'],
 [u'1', u'100', u'a'],
 [u'1', u'101', u'b'],
 [u'2', u'102', u'c'],
 [u'3', u'103', u'b'],
 [u'3', u'103', u'c'],
 [u'4', u'104', u'a'],
 [u'4', u'105', u'b']]
)
</code>```

My solution so far:

1. Group products in orders:

```<code>order_prod = test.map(lambda x: [x[1],([x[2]])])
order_prod = order_prod.reduceByKey(lambda a,b: a + b)
order_prod.collect()
</code>```

which results in:

```<code>[(u'102', [u'c']),
 (u'103', [u'b', u'c']),
 (u'100', [u'a', u'a']),
 (u'104', [u'a']),
 (u'101', [u'b']),
 (u'105', [u'b'])]
</code>```

2. Group orders in customers:

```<code>client_order = test.map(lambda x: [x[0],[(x[1])]])
df_co = sqlContext.createDataFrame(client_order)
df_co = df_co.distinct()
client_order = df_co.rdd.map(list)
client_order = client_order.reduceByKey(lambda a,b: a + b)
client_order.collect()
</code>```

which results in:

```<code>[(u'4', [u'105', u'104']),
 (u'3', [u'103']),
 (u'2', [u'102']),
 (u'1', [u'100', u'101'])]
</code>```

Then I want to have a list like this:

```<code>[[[u'a', u'a'],[u'b']], [[u'c']], [[u'b', u'c']], [[u'a'],[u'b']]]
</code>```

答:
Here is the solution using PySpark dataframe (not that I use PySpark 2.1). First, you have to transform RDD to Dataframe.

```<code>df = test.toDF(['clientId', 'orderId', 'product'])
</code>```

And this is the snippet to group the dataframe. Basic idea is to group by clientId and orderId first and aggregate product column together. Then group again by only clientId.

```<code>import pyspark.sql.functions as func

df_group = df.groupby(['clientId', 'orderId']).agg(func.collect_list('product').alias('product_list'))
df_group_2 = df_group[['clientId', 'product_list']].\
    groupby('clientId').\
    agg(func.collect_list('product_list').alias('product_list_group')).\
    sort('clientId', ascending=True)
df_group_2.rdd.map(lambda x: x.product_list_group).collect() # collect output here
</code>```

Result is the following:

```<code>[[['a', 'a'], ['b']], [['c']], [['b', 'c']], [['b'], ['a']]]
</code>```

Body:
I want to use PrefixSpan sequence mining in pyspark. The format of data that I need to have is the following:

[[['a', 'b'], ['c']],  [['a'], ['c', 'b'], ['a', 'b']],  [['a', 'b'], ['e']], [['f']]]

where the innermost elements are productIds, then there are orders (containing list of products) and then there are clients (containing lists of orders).

My data has transactional format:

clientId orderId product

where orderId has multiple rows for separate products and clientId has multiple rows for separate orders.

Sample data:

test = sc.parallelize([[u'1', u'100', u'a'],
 [u'1', u'100', u'a'],
 [u'1', u'101', u'b'],
 [u'2', u'102', u'c'],
 [u'3', u'103', u'b'],
 [u'3', u'103', u'c'],
 [u'4', u'104', u'a'],
 [u'4', u'105', u'b']]
)

My solution so far:

1. Group products in orders:

order_prod = test.map(lambda x: [x[1],([x[2]])])
order_prod = order_prod.reduceByKey(lambda a,b: a + b)
order_prod.collect()

which results in:

[(u'102', [u'c']),
 (u'103', [u'b', u'c']),
 (u'100', [u'a', u'a']),
 (u'104', [u'a']),
 (u'101', [u'b']),
 (u'105', [u'b'])]

2. Group orders in customers:

client_order = test.map(lambda x: [x[0],[(x[1])]])
df_co = sqlContext.createDataFrame(client_order)
df_co = df_co.distinct()
client_order = df_co.rdd.map(list)
client_order = client_order.reduceByKey(lambda a,b: a + b)
client_order.collect()

which results in:

[(u'4', [u'105', u'104']),
 (u'3', [u'103']),
 (u'2', [u'102']),
 (u'1', [u'100', u'101'])]

Then I want to have a list like this:

[[[u'a', u'a'],[u'b']], [[u'c']], [[u'b', u'c']], [[u'a'],[u'b']]]

Body:
Here is the solution using PySpark dataframe (not that I use PySpark 2.1). First, you have to transform RDD to Dataframe.

df = test.toDF(['clientId', 'orderId', 'product'])

And this is the snippet to group the dataframe. Basic idea is to group by clientId and orderId first and aggregate product column together. Then group again by only clientId.

import pyspark.sql.functions as func

df_group = df.groupby(['clientId', 'orderId']).agg(func.collect_list('product').alias('product_list'))
df_group_2 = df_group[['clientId', 'product_list']].\
    groupby('clientId').\
    agg(func.collect_list('product_list').alias('product_list_group')).\
    sort('clientId', ascending=True)
df_group_2.rdd.map(lambda x: x.product_list_group).collect() # collect output here

Result is the following:

[[['a', 'a'], ['b']], [['c']], [['b', 'c']], [['b'], ['a']]]


问:
Embedding Share Icons Inline Within Another View
I am attempting to implement a "Share" feature in my iOS app with a similar look and feel to that of the Google Photos iOS app:

The bottom two rows of icons are what I care about. They look nearly identical to those displayed when using the UIActivityViewController.

In the Google Photos app, these icons appear inline with the "select photos" portion of the screen (e.g. you can still interact with the upper portion of the screen). However, the documentation for the UIActivityViewController states that "On iPhone and iPod touch, you must present [the view controller] modally."

This is the difference that is really important to me -- I'd like for the "share" icons to display inline with the rest of my content, rather than having a modal that is displayed on top of my content.

Is it possible to use the UIActivityViewController to achieve a similar effect shown in the screenshot above? If not, is there a recommended approach that I might use to implement this sort of functionality?

答:
Okay, I thought about this and I did some intensive research on the web but nobody ever seemed to needed to modify it like you want. So here are my guesses how Google engineers solved this:

They reverse engineered the UIActivityViewController and call some private APIs to get the same icons to show up and the reordering controllers

They use the UIViewController transitioning API and hack the view hierarchy of a modally presented UIActivityViewController, removing the cancel button and adding some custom views on top of its view

An indicator for the second option could be that the top of the presented "sheet" has a white background while the bottom has the greyish color.

Unfortunately I'm not very fit with the transitioning API as I'm just about to learn it but my understanding is that you can provide a custom object as the transitioning delegate.

This object then gets called when you present/dismiss or push/pop a UIViewController. It will get a reference to both, the presenting and the presented view controller and you can have fun with both of their views.

This should make it "quiet" easy to remove and add some subviews, change frames and colors etc while still having all the default behavior.

I hope this answer helps you to achieve what you want. However, be aware that the structure of the controller could change at any time so always make sure to also test agains betas so that you don't get caught by surprise when apple releases an update which breaks your UI. :)


问:
Javascript "Member not found" error in IE8
I'm trying to debug the following block of Javascript code to see what the issue is. I'm getting an error that says "Member not found" on the line ```constructor = function() {``` in the extend:function() method.

I'm not very good with Javascript, and I didn't write this, so I'm kind of lost on what the issue is. The error only occurs in IE8, it works fine in IE7 and Firefox.

```<code>var Class = {
  create: function() {
    return function() {
        if(this.destroy) Class.registerForDestruction(this);
          if(this.initialize) this.initialize.apply(this, arguments);
      }
  },

  extend: function(baseClassName) {
    constructor = function() {
        var i;

          this[baseClassName] = {}
        for(i in window[baseClassName].prototype) {
            if(!this[i]) this[i] = window[baseClassName].prototype[i];
            if(typeof window[baseClassName].prototype[i] == 'function') {
                this[baseClassName][i] = window[baseClassName].prototype[i].bind(this);
            }
        }

        if(window[baseClassName].getInheritedStuff) {
            window[baseClassName].getInheritedStuff.apply(this);
        }

        if(this.destroy) Class.registerForDestruction(this);
          if(this.initialize) this.initialize.apply(this, arguments);
    }

    constructor.getInheritedStuff = function() {
        this[baseClassName] = {}
        for(i in window[baseClassName].prototype) {
            if(!this[i]) this[i] = window[baseClassName].prototype[i];
            if(typeof window[baseClassName].prototype[i] == 'function') {
                this[baseClassName][i] = window[baseClassName].prototype[i].bind(this);
            }
        }

        if(window[baseClassName].getInheritedStuff) {
            window[baseClassName].getInheritedStuff.apply(this);
        }
    }

    return constructor;

  },

  objectsToDestroy : [],
  registerForDestruction: function(obj) {
    if(!Class.addedDestructionLoader) {
            Event.observe(window, 'unload', Class.destroyAllObjects);
        Class.addedDestructionLoader = true;
    }
    Class.objectsToDestroy.push(obj);
  },

  destroyAllObjects: function() {
    var i,item;
    for(i=0;item=Class.objectsToDestroy[i];i++) {
        if(item.destroy) item.destroy();
    }
    Class.objectsToDestroy = null;
  }
}
</code>```

答: i had the same problem. IE8 treats 'class' variable as a method and freeze. Try to rename it to something else</p>

Body:
I'm trying to debug the following block of Javascript code to see what the issue is. I'm getting an error that says "Member not found" on the line
constructor = function() {
 in the extend:function() method.

I'm not very good with Javascript, and I didn't write this, so I'm kind of lost on what the issue is. The error only occurs in IE8, it works fine in IE7 and Firefox.

var Class = {
  create: function() {
    return function() {
        if(this.destroy) Class.registerForDestruction(this);
          if(this.initialize) this.initialize.apply(this, arguments);
      }
  },

  extend: function(baseClassName) {
    constructor = function() {
        var i;

          this[baseClassName] = {}
        for(i in window[baseClassName].prototype) {
            if(!this[i]) this[i] = window[baseClassName].prototype[i];
            if(typeof window[baseClassName].prototype[i] == 'function') {
                this[baseClassName][i] = window[baseClassName].prototype[i].bind(this);
            }
        }

        if(window[baseClassName].getInheritedStuff) {
            window[baseClassName].getInheritedStuff.apply(this);
        }

        if(this.destroy) Class.registerForDestruction(this);
          if(this.initialize) this.initialize.apply(this, arguments);
    }

    constructor.getInheritedStuff = function() {
        this[baseClassName] = {}
        for(i in window[baseClassName].prototype) {
            if(!this[i]) this[i] = window[baseClassName].prototype[i];
            if(typeof window[baseClassName].prototype[i] == 'function') {
                this[baseClassName][i] = window[baseClassName].prototype[i].bind(this);
            }
        }

        if(window[baseClassName].getInheritedStuff) {
            window[baseClassName].getInheritedStuff.apply(this);
        }
    }

    return constructor;

  },

  objectsToDestroy : [],
  registerForDestruction: function(obj) {
    if(!Class.addedDestructionLoader) {
            Event.observe(window, 'unload', Class.destroyAllObjects);
        Class.addedDestructionLoader = true;
    }
    Class.objectsToDestroy.push(obj);
  },

  destroyAllObjects: function() {
    var i,item;
    for(i=0;item=Class.objectsToDestroy[i];i++) {
        if(item.destroy) item.destroy();
    }
    Class.objectsToDestroy = null;
  }
}


问:
Firebase Datatabase - Query object inside another object
I wanted to get this book by its title, however this query is returning me all nodes without any filtering. Any suggestions on how to get into volumeInfo and filter by title?

```<code>mDatabaseReference.child(userId)
                .child(REF_FOLDERS)
                .child(REF_MY_BOOKS_FOLDER)
                .child(REF_BOOKS)
                .orderByChild("volumeInfo")
                .startAt(bookQuery,"title")
                .addListenerForSingleValueEvent(buildValueEventListener(onDataSnapshotListener));
</code>```

答:
Firebase have the method "equalTo" that filter the value inside an attribute from the object, like "volumeInfo" is in your object.
If you do like this, will work:

```<code>mDatabaseReference.child(userId)
            .child(REF_FOLDERS)
            .child(REF_MY_BOOKS_FOLDER)
            .child(REF_BOOKS)
            .orderByChild("volumeInfo")
            .equalTo("titleSearched")
            .then (function (snapshot){
                console.log(snapshot.val()) // will print the title searched by volumeInfo
            })
</code>```

This may help you.

Body:
I wanted to get this book by its title, however this query is returning me all nodes without any filtering. Any suggestions on how to get into volumeInfo and filter by title?

mDatabaseReference.child(userId)
                .child(REF_FOLDERS)
                .child(REF_MY_BOOKS_FOLDER)
                .child(REF_BOOKS)
                .orderByChild("volumeInfo")
                .startAt(bookQuery,"title")
                .addListenerForSingleValueEvent(buildValueEventListener(onDataSnapshotListener));

Body:
Firebase have the method "equalTo" that filter the value inside an attribute from the object, like "volumeInfo" is in your object.
If you do like this, will work:

mDatabaseReference.child(userId)
            .child(REF_FOLDERS)
            .child(REF_MY_BOOKS_FOLDER)
            .child(REF_BOOKS)
            .orderByChild("volumeInfo")
            .equalTo("titleSearched")
            .then (function (snapshot){
                console.log(snapshot.val()) // will print the title searched by volumeInfo
            })

This may help you.


问:
Outlook VBA Macro: Best way to indicate 'please wait'
What's the best practice for indicating to the user that a Macro is running within Outlook ?
The macro can take around 1-30 seconds to complete.

I want to avoid a modal 'msgbox' popping up before the macro is run, as this can be annoying.

I would rather avoid the hourglass cursor if possible, and wondered if there was a better way.

Is there a way of placing a non-modal 'status' message up, whilst the macro is running?

(The macro I have runs against the currently selected mailItem - and it launched by a button on the Quick Access Toolbar).

答:
Expanding on @76mel's answer, a nice way to do this is with a non-modal userform. Make something really simple with just a label and caption like this:

What I like to do is have the userform set as:

Non modal (in properties F4, set ShowModal to false)

This means you can click outside the status bar and it doesn't stop you.

I set the StartupPosition to 0-Manual and Top and Left to something like 100 so that the Status form appears in the top left corner of the screen (out of the way of any other messages which appear in centre by default)

Set the label's value to some default text for when the Userform first loads

```<code>Public strStatus As String
Public Const defaultStatus As String = "Default status text" 'set this to whatever you want

Sub statusReporter()
frmStatus.Show
'''
'Your code here
'''
    frmStatus.lblStatus = "Step 1"
    '...
    frmStatus.lblStatus = "Step 2"
    '...
'''
'Unload the form
'''
frmStatus.lblStatus = defaultStatus
frmStatus.Hide
End Sub
</code>```

Note, like with Excel's Application.Statusbar you must reset the userform to its default value if you plan to use it later on in the same instance of Excel
Optionally use this too

```<code>'Written By RobDog888 - VB/Office Guru™
'Add a Command Button so you can toggle the userform's topmost effect

Private Declare Function FindWindow Lib "user32.dll" Alias "FindWindowA" ( _
                    ByVal lpClassName As String, _
                    ByVal lpWindowName As String) As Long

Private Declare Function SetWindowPos Lib "user32" ( _
                    ByVal hwnd As Long, _
                    ByVal hWndInsertAfter As Long, _
                    ByVal X As Long, _
                    ByVal Y As Long, _
                    ByVal cx As Long, _
                    ByVal cy As Long, _
                    ByVal wFlags As Long) As Long

Private Const HWND_TOPMOST = -1
Private Const HWND_NOTOPMOST = -2
Private Const SWP_NOMOVE = &H2
Private Const SWP_NOSIZE = &H1
Private mlHwnd As Long

Private Sub UserForm_Initialize()
Dim overTim As Single
overTim = Timer
    mlHwnd = FindWindow("ThunderDFrame", "Status") 'Change "Status" to match your userforms caption
    Do While mlHwnd = 0 And Timer - overTim < 5
        mlHwnd = FindWindow("ThunderDFrame", "Status")
        DoEvents
    Loop
    'Set topmost
    SetWindowPos mlHwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE Or SWP_NOSIZE
End Sub
</code>```

in the userform code itself to keep it on top always

Body:
Expanding on @76mel's answer, a nice way to do this is with a non-modal userform. Make something really simple with just a label and caption like this:

What I like to do is have the userform set as:

Non modal (in properties F4, set ShowModal to false)

This means you can click outside the status bar and it doesn't stop you.

I set the StartupPosition to 0-Manual and Top and Left to something like 100 so that the Status form appears in the top left corner of the screen (out of the way of any other messages which appear in centre by default)

Set the label's value to some default text for when the Userform first loads

Public strStatus As String
Public Const defaultStatus As String = "Default status text" 'set this to whatever you want

Sub statusReporter()
frmStatus.Show
'''
'Your code here
'''
    frmStatus.lblStatus = "Step 1"
    '...
    frmStatus.lblStatus = "Step 2"
    '...
'''
'Unload the form
'''
frmStatus.lblStatus = defaultStatus
frmStatus.Hide
End Sub

Note, like with Excel's Application.Statusbar you must reset the userform to its default value if you plan to use it later on in the same instance of Excel
Optionally use this too

'Written By RobDog888 - VB/Office Guru™
'Add a Command Button so you can toggle the userform's topmost effect

Private Declare Function FindWindow Lib "user32.dll" Alias "FindWindowA" ( _
                    ByVal lpClassName As String, _
                    ByVal lpWindowName As String) As Long

Private Declare Function SetWindowPos Lib "user32" ( _
                    ByVal hwnd As Long, _
                    ByVal hWndInsertAfter As Long, _
                    ByVal X As Long, _
                    ByVal Y As Long, _
                    ByVal cx As Long, _
                    ByVal cy As Long, _
                    ByVal wFlags As Long) As Long

Private Const HWND_TOPMOST = -1
Private Const HWND_NOTOPMOST = -2
Private Const SWP_NOMOVE = &H2
Private Const SWP_NOSIZE = &H1
Private mlHwnd As Long

Private Sub UserForm_Initialize()
Dim overTim As Single
overTim = Timer
    mlHwnd = FindWindow("ThunderDFrame", "Status") 'Change "Status" to match your userforms caption
    Do While mlHwnd = 0 And Timer - overTim < 5
        mlHwnd = FindWindow("ThunderDFrame", "Status")
        DoEvents
    Loop
    'Set topmost
    SetWindowPos mlHwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE Or SWP_NOSIZE
End Sub

in the userform code itself to keep it on top always


问:
Android Realm for-loop - RealmResults are removed during looping
I have some code running in an IntentService, doing image uploads.  It starts by fetching posts that are "queued" for upload, then it loops through those and makes synchronous Retrofit calls to upload images.  Fairly straight-forward.  See code for reference:

```<code>final RealmResults<Post> posts = realm.where(Post.class)
            .equalTo("uniqueCode", uniqueCode)
            .equalTo("queued", true)
            .isEmpty("url")
            .findAll();

Log.d(TAG, "post count: " + posts.size());

if (posts != null && posts.size() > 0) {
    for (int i = 0; i < posts.size(); i++) {
        Log.d(TAG, "posts count now: " + posts.size());

        Post post = posts.get(i);

        Post submittedPost = api.uploadPhoto(<params>); // Retrofit call, which works fine

        if (submittedPost != null) {
            realm.beginTransaction();
            post.setQueued(false);
            post.setUrl(submittedPost.getUrl());
            realm.commitTransaction();

            sendBroadcastUpdate(); // This updates the UI in places
        }
    }
}
</code>```

Oddly enough, each time it goes through the for-loop, the size of the results ("posts" in my case above) goes down by one - this is confirmed by my Log output that decrements by one each time, so it only gets through a few of the results.  It's almost as if each time I'm committing the Realm transaction during the looping, it's updating my fetched query results, even though that array is set to be final.

I confirmed that it doesn't do this if I don't set those values ('queued' and 'url').  Which tells me it's updating the results somehow.  I've tried different things, such as a while-loop (i.e. "while (posts.size() > 0)"), but it gets through 2-3 of them, and then all of a sudden the size of "posts" is immediately 0, for no reason at all that I can see.

I've also tried doing the begin/commit before and after the loop, but it yields similar results.  Same goes for if I convert it to an array before processing.  It seems that it always gets through a few of them, and then the size is automatically set to 0, so it exits the loop.

This strikes me as very bizarre, especially since I set the results to be "final" - is this expected behavior?  Does anyone know a way around this, by chance?

For reference, we are using Realm version: 0.86.

答: This is a normal behavior of an Iterator. Once you call .next(), you get the item and it is removed from the iterator. If you want to keep items, write a utility to convert an iterator to an ArrayList or some similar thing. You can read more about iterators here: https://www.tutorialspoint.com/java/java_using_iterator.htm</p>

Body:
I have some code running in an IntentService, doing image uploads.  It starts by fetching posts that are "queued" for upload, then it loops through those and makes synchronous Retrofit calls to upload images.  Fairly straight-forward.  See code for reference:

final RealmResults<Post> posts = realm.where(Post.class)
            .equalTo("uniqueCode", uniqueCode)
            .equalTo("queued", true)
            .isEmpty("url")
            .findAll();

Log.d(TAG, "post count: " + posts.size());

if (posts != null && posts.size() > 0) {
    for (int i = 0; i < posts.size(); i++) {
        Log.d(TAG, "posts count now: " + posts.size());

        Post post = posts.get(i);

        Post submittedPost = api.uploadPhoto(<params>); // Retrofit call, which works fine

        if (submittedPost != null) {
            realm.beginTransaction();
            post.setQueued(false);
            post.setUrl(submittedPost.getUrl());
            realm.commitTransaction();

            sendBroadcastUpdate(); // This updates the UI in places
        }
    }
}

Oddly enough, each time it goes through the for-loop, the size of the results ("posts" in my case above) goes down by one - this is confirmed by my Log output that decrements by one each time, so it only gets through a few of the results.  It's almost as if each time I'm committing the Realm transaction during the looping, it's updating my fetched query results, even though that array is set to be final.

I confirmed that it doesn't do this if I don't set those values ('queued' and 'url').  Which tells me it's updating the results somehow.  I've tried different things, such as a while-loop (i.e. "while (posts.size() > 0)"), but it gets through 2-3 of them, and then all of a sudden the size of "posts" is immediately 0, for no reason at all that I can see.

I've also tried doing the begin/commit before and after the loop, but it yields similar results.  Same goes for if I convert it to an array before processing.  It seems that it always gets through a few of them, and then the size is automatically set to 0, so it exits the loop.

This strikes me as very bizarre, especially since I set the results to be "final" - is this expected behavior?  Does anyone know a way around this, by chance?

For reference, we are using Realm version: 0.86.


问:
Using Python with Tkinter, how can I make a button press do a different thing depending on which option is selected in the option menu?
I'm making a simple GUI, and my goal right now is for the user to select an option (kinematics or electricity) and then they would press the button to move on to a new screen for the one they selected. Currently, the button will do the same thing no matter which is selected, and I don't know how to change that. I'm using Python 3.6.1 </p>

```<code>from tkinter import *
import tkinter.font

bg_color1 = "#008B8B"

abc = Tk()

abc.title("Physics Problem Solver")
abc.rowconfigure(0, weight=1)
abc.columnconfigure(0, weight=1)

helvetica_bold_16 = tkinter.font.Font(
    root = abc,
    family="Helvetica",
    weight="bold",
    size=16)

helvetica_bold_12 = tkinter.font.Font(
    root = abc,
    family="Helvetica",
    weight="bold",
    size=12)

app = Frame(abc,
    bd=6,
    relief="groove",
    bg=bg_color1)
app.rowconfigure(0, weight=1)
app.columnconfigure(0, weight=1)
app.grid(sticky=N+S+E+W)

msg1 = Message(app,
    text = "Welcome to the Physics Problem Solver!",
    font=helvetica_bold_16,
    bg=bg_color1,
    fg="white",
    justify="center",
    relief="flat")
msg1.grid(pady=15)

def callback1():
    toplevel = Toplevel()
    toplevel.title("Window 2")
    toplevel.focus_set()

optionList = ("Kinematics",
    "Electricity")
om1v= StringVar()
om1v.set(optionList[0])

om1 = OptionMenu(app,
    om1v,
    "Kinematics",
    "Electricity")
om1.grid(pady=20)

b1= Button(app,
    text="Go!",
    width=5,
    activebackground="#007070",
    activeforeground="#00ACAC",
    fg="black",
    justify="center",
    font=helvetica_bold_12,
    relief="raised",
    command=callback1)
b1.grid(pady=20)

abc.mainloop()
</code>```

答:
There's nothing special you need to do. In your callback you can get the value of the option menu and then do whatever is appropriate.</p>

```<code>def callback1():
    if om1v.get() == "Kinematics":
        do_kinematics
    else:
        do_electricity()
</code>```

Body:
I'm making a simple GUI, and my goal right now is for the user to select an option (kinematics or electricity) and then they would press the button to move on to a new screen for the one they selected. Currently, the button will do the same thing no matter which is selected, and I don't know how to change that. I'm using Python 3.6.1

from tkinter import *
import tkinter.font

bg_color1 = "#008B8B"

abc = Tk()

abc.title("Physics Problem Solver")
abc.rowconfigure(0, weight=1)
abc.columnconfigure(0, weight=1)

helvetica_bold_16 = tkinter.font.Font(
    root = abc,
    family="Helvetica",
    weight="bold",
    size=16)

helvetica_bold_12 = tkinter.font.Font(
    root = abc,
    family="Helvetica",
    weight="bold",
    size=12)

app = Frame(abc,
    bd=6,
    relief="groove",
    bg=bg_color1)
app.rowconfigure(0, weight=1)
app.columnconfigure(0, weight=1)
app.grid(sticky=N+S+E+W)

msg1 = Message(app,
    text = "Welcome to the Physics Problem Solver!",
    font=helvetica_bold_16,
    bg=bg_color1,
    fg="white",
    justify="center",
    relief="flat")
msg1.grid(pady=15)

def callback1():
    toplevel = Toplevel()
    toplevel.title("Window 2")
    toplevel.focus_set()

optionList = ("Kinematics",
    "Electricity")
om1v= StringVar()
om1v.set(optionList[0])

om1 = OptionMenu(app,
    om1v,
    "Kinematics",
    "Electricity")
om1.grid(pady=20)

b1= Button(app,
    text="Go!",
    width=5,
    activebackground="#007070",
    activeforeground="#00ACAC",
    fg="black",
    justify="center",
    font=helvetica_bold_12,
    relief="raised",
    command=callback1)
b1.grid(pady=20)

abc.mainloop()

Body:
There's nothing special you need to do. In your callback you can get the value of the option menu and then do whatever is appropriate.

def callback1():
    if om1v.get() == "Kinematics":
        do_kinematics
    else:
        do_electricity()


问:
CoqIDE 8.5 default font
Sorry for this trivial question --- What is CoqIDE's default font in Coq 8.5? Trying out Coq 8.6 w/ nix-shell -p coq_8_6 --run coqide changed my old CoqIDE font (and keybindings); I want them back but don't remember the font name. The exact version (not sure if this matters) is 8.5pl1. Sadly, a reboot and even nix-env --rollback didn't restore the settings (my 8.5 was installed w/ nix and nix-shell -p coq_8_6 --run coqide shouldn't install anything AFAIK)

答:
For whatever reason, CoqIDE >= 8.5pl3 overrides the system's default Monospace font1, while CoqIDE <= 8.5pl1 uses the default. The first step is to find the system's default:

```<code>fc-match monospace
</code>```

DejaVuSansMono.ttf: "DejaVu Sans Mono" "Book"

The second step is to change the font (under Edit > Preferences) to whatever fc-match monospace gave you.

1 Possibly w/ FreeMono

Title: CoqIDE 8.5 default font

Body:
For whatever reason, CoqIDE >= 8.5pl3 overrides the system's default Monospace font1, while CoqIDE <= 8.5pl1 uses the default. The first step is to find the system's default:

fc-match monospace

DejaVuSansMono.ttf: "DejaVu Sans Mono" "Book"

The second step is to change the font (under Edit > Preferences) to whatever fc-match monospace gave you.

1 Possibly w/ FreeMono


问:
How to determine appropriate strftime format from a date string?
The dateutil parser does a great job of correctly guessing the date and time from a wide variety of sources.

We are processing files in which each file uses only one date/time format, but the format varies between files. Profiling shows a lot of time being used by dateutil.parser.parse.  Since it only needs to be determined once per file, implementing something that isn't guessing the format each time could speed things up.

I don't actually know the formats in advance and I'll still need to infer the format.  Something like:

```<code>from MysteryPackage import date_string_to_format_string
import datetime

# e.g. mystring = '1 Jan 2016'
myformat = None

...

# somewhere in a loop reading from a file or connection:
if myformat is None:
    myformat = date_string_to_format_string(mystring)

# do the usual checks to see if that worked, then:
mydatetime = datetime.strptime(mystring, myformat)
</code>```

Is there such a function?

答:
You can write your own parser:

```<code>import datetime

class DateFormatFinder:
    def __init__(self):
        self.fmts = []

    def add(self,fmt):
        self.fmts.append(fmt)

    def find(self, ss):
        for fmt in self.fmts:
            try:
                datetime.datetime.strptime(ss, fmt)
                return fmt
            except:
                pass
        return None
</code>```

You can use it as follows:

```<code>>>> df = DateFormatFinder()
>>> df.add('%m/%d/%y %H:%M')
>>> df.add('%m/%d/%y')
>>> df.add('%H:%M')

>>> df.find("01/02/06 16:30")
'%m/%d/%y %H:%M'
>>> df.find("01/02/06")
'%m/%d/%y'
>>> df.find("16:30")
'%H:%M'
>>> df.find("01/02/06 16:30")
'%m/%d/%y %H:%M'
>>> df.find("01/02/2006")
</code>```

However, It is not so simple as dates can be ambiguous and their format can not be determined without some context.

```<code>>>> datetime.strptime("01/02/06 16:30", "%m/%d/%y %H:%M") # us format
datetime.datetime(2006, 1, 2, 16, 30)
>>> datetime.strptime("01/02/06 16:30", "%d/%m/%y %H:%M") # european format
datetime.datetime(2006, 2, 1, 16, 30)
</code>```

Body:
The dateutil parser does a great job of correctly guessing the date and time from a wide variety of sources.

We are processing files in which each file uses only one date/time format, but the format varies between files. Profiling shows a lot of time being used by dateutil.parser.parse.  Since it only needs to be determined once per file, implementing something that isn't guessing the format each time could speed things up.

I don't actually know the formats in advance and I'll still need to infer the format.  Something like:

from MysteryPackage import date_string_to_format_string
import datetime

# e.g. mystring = '1 Jan 2016'
myformat = None

...

# somewhere in a loop reading from a file or connection:
if myformat is None:
    myformat = date_string_to_format_string(mystring)

# do the usual checks to see if that worked, then:
mydatetime = datetime.strptime(mystring, myformat)

Is there such a function?

Body:
You can write your own parser:

import datetime

class DateFormatFinder:
    def __init__(self):
        self.fmts = []

    def add(self,fmt):
        self.fmts.append(fmt)

    def find(self, ss):
        for fmt in self.fmts:
            try:
                datetime.datetime.strptime(ss, fmt)
                return fmt
            except:
                pass
        return None

You can use it as follows:

>>> df = DateFormatFinder()
>>> df.add('%m/%d/%y %H:%M')
>>> df.add('%m/%d/%y')
>>> df.add('%H:%M')

>>> df.find("01/02/06 16:30")
'%m/%d/%y %H:%M'
>>> df.find("01/02/06")
'%m/%d/%y'
>>> df.find("16:30")
'%H:%M'
>>> df.find("01/02/06 16:30")
'%m/%d/%y %H:%M'
>>> df.find("01/02/2006")

However, It is not so simple as dates can be ambiguous and their format can not be determined without some context.

>>> datetime.strptime("01/02/06 16:30", "%m/%d/%y %H:%M") # us format
datetime.datetime(2006, 1, 2, 16, 30)
>>> datetime.strptime("01/02/06 16:30", "%d/%m/%y %H:%M") # european format
datetime.datetime(2006, 2, 1, 16, 30)


问:
splitting large file into small files
I have a text file which has thousands of number values like
1
2
3
4
5
.
.
.
.
n

I know we can use awk to separate these values. But is there a way in which one can fetch first 10,20,40,80,160....,n values in different text files.

I was using python to do so but it takes a lot of time to separate these files.Here is the sample code for python

```<code>import numpy as np
from itertools import islice
data = np.loadtxt('ABC.txt',
                 unpack=True,
                 delimiter=',',
                 skiprows=1)
n = 10
iterator = list(islice(data[0], n))
for item in range(n):
np.savetxt('output1.txt',iterator,delimiter=',',fmt='%10.5f')

iterator = list(islice(data[0], n*2))
for item in iterator:
np.savetxt('output2.txt', iterator, delimiter=',',fmt='%10.5f')

iterator = list(islice(data[0], n*4))
for item in iterator:
np.savetxt('output3.txt', iterator, delimiter=',',fmt='%10.5f')

iterator = list(islice(data[0], n*8))
for item in iterator:
np.savetxt('output4.txt', iterator, delimiter=',',fmt='%10.5f')
</code>```

and so on.

Is there a better way to do this in bash or in python. Thank you in advance!

答:
You didn't provide any sample input and expected output and the text of your questions is ambiguous so this is just a guess but this MAY be what you're looking for:

```<code>$ seq 1000 | awk -v c=10 'NR==c{print; c=2*c}'
10
20
40
80
160
320
640
</code>```

If not then edit your question to clarify.

Title: splitting large file into small files

Body:
I have a text file which has thousands of number values like
1
2
3
4
5
.
.
.
.
n

I know we can use awk to separate these values. But is there a way in which one can fetch first 10,20,40,80,160....,n values in different text files.

I was using python to do so but it takes a lot of time to separate these files.Here is the sample code for python

import numpy as np
from itertools import islice
data = np.loadtxt('ABC.txt',
                 unpack=True,
                 delimiter=',',
                 skiprows=1)
n = 10
iterator = list(islice(data[0], n))
for item in range(n):
np.savetxt('output1.txt',iterator,delimiter=',',fmt='%10.5f')

iterator = list(islice(data[0], n*2))
for item in iterator:
np.savetxt('output2.txt', iterator, delimiter=',',fmt='%10.5f')

iterator = list(islice(data[0], n*4))
for item in iterator:
np.savetxt('output3.txt', iterator, delimiter=',',fmt='%10.5f')

iterator = list(islice(data[0], n*8))
for item in iterator:
np.savetxt('output4.txt', iterator, delimiter=',',fmt='%10.5f')

and so on.

Is there a better way to do this in bash or in python. Thank you in advance!

Body:
You didn't provide any sample input and expected output and the text of your questions is ambiguous so this is just a guess but this MAY be what you're looking for:

$ seq 1000 | awk -v c=10 'NR==c{print; c=2*c}'
10
20
40
80
160
320
640

If not then edit your question to clarify.


答:
an inefficient but quick to implement apprach

```<code>s=5; for i in {1..10}; do ((s*=2)); head -$s file > sub$i; done
</code>```

since the files are overlapping, there will be better ways, but based on the size of the file and how many times it needs to be repeated this might be good enough.

Title: splitting large file into small files

Body:
an inefficient but quick to implement apprach

s=5; for i in {1..10}; do ((s*=2)); head -$s file > sub$i; done

since the files are overlapping, there will be better ways, but based on the size of the file and how many times it needs to be repeated this might be good enough.


问:
What is the right way to include Qt headers?
So far I know several ways to #include Qt classes:

#include <QtModule>

This brings all classes of a specific module, for example QDomDocument, QDomElement, QDomNode and numerous others from #include <QtXml>.

#include <QClassName>

This adds declaration of a specific class one may want to use, e.g. QEvent, QStringList, QFile.

#include <qcstyleheader.h>

This has effect of the previous method, except for differently looking header name.

So I wonder, are there any other ways to #include Qt classes? Are they equivalent, or are some of them preferred to others because of some reasons? Does this depend on #include-ing inside a .cpp or a .h file? Does this influence compilation speed and size of the executable?

In short, what is the best way to go?

答:
I don't think there is any universally right way of including... My preferred way is the second one, since it's easiest - you just do it for every class you use in your file, a lot less thinking is needed.

As for the compilation speed, yes, Qt headers happen to take a while to compile. If you want to compile faster, #include everything you need in .cpp files. Sometimes you need to include in .h files - if you declare a class, you always need to #include its base class, and classes of any members that you keep by value inside class or pass by value in class functions. However, for those members and function parameters that are declared as pointers, smart pointers or references, you may substitute #include with "class foo;" declaration. Then your header will compile faster, but you still need to #include these classes whenever you actually use them by value.


问:
Checkbox doesnt update on react on child even if the parent state update?
This is the code from the parent:

```<code>_handleSelectedTodo(e) {
  e.preventDefault();
  this.setState({checkedIds: [...this.state.checkedIds, e.target.value]});
}
// render () { ...
<ul>
{todos.map((todo,todoIndex) => // The map method has default argument on second index, the index of the current todo in map execution. We use it so we do not have to use findIndex when we need to dispatch action that needs index of a specific todo
  <Todo
    key={todo.id}
    {...todo} // pass all the todo property
    onClick={() => onTodoClick(todo.id)}
    onTrashClick={() => onDeleteClick(todoIndex)}
    handleSelectedTodo = {this._handleSelectedTodo}
    checked={Boolean(this.state.checkedIds.includes(todo.id))}
  />
)}
</code>```

This is what I tried since assigning props on checkbox doesn't update on the Child Todo code, checked can be true or false that will depend on props:

```<code>componentWillMount() {
  this.setState({ checked: this.props.checked })
}
// render() { ...
<input
  checked={this.state.checked}
  onChange={handleSelectedTodo}
  type="checkbox"
  value={id}
></input>
</code>```

Checking on the checkbox updates the parent component state but the checkbox on child is not checked. help?

答:
This code can also be written this way:-

```<code>_handleSelectedTodo(e) {
  e.preventDefault();
  this.setState({checkedIds: [...this.state.checkedIds, e.target.value]});
}
render () { ...
<ul>
{todos.map((todo,todoIndex) => {
  let isChecked = (this.state.checkedIds.indexOf(todo.id) >= 0);
  return (
     <Todo
       key={todo.id}
       {...todo} // pass all the todo property
       onClick={(id) => onTodoClick(todo.id)} //This event should be binded to 'this' inside the constructor
       onTrashClick={(todoIndex) => onDeleteClick(todoIndex)}
       handleSelectedTodo = {this._handleSelectedTodo}
       checked={isChecked}
     />
  )
 });
}
</code>```

This child component should depend on it's parent state for it's checked property

```<code><input
  checked={this.props.checked}
  onChange={handleSelectedTodo}
  type="checkbox"
  value={id}
></input>
</code>```

If you want to keep the checked property of child as a state of child as well, then what Mayank said about componentWillReceiveProps would be the right approach.

Body:
This is the code from the parent:

_handleSelectedTodo(e) {
  e.preventDefault();
  this.setState({checkedIds: [...this.state.checkedIds, e.target.value]});
}
// render () { ...

{todos.map((todo,todoIndex) => // The map method has default argument on second index, the index of the current todo in map execution. We use it so we do not have to use findIndex when we need to dispatch action that needs index of a specific todo
  <Todo
    key={todo.id}
    {...todo} // pass all the todo property
    onClick={() => onTodoClick(todo.id)}
    onTrashClick={() => onDeleteClick(todoIndex)}
    handleSelectedTodo = {this._handleSelectedTodo}
    checked={Boolean(this.state.checkedIds.includes(todo.id))}
  />
)}

This is what I tried since assigning props on checkbox doesn't update on the Child Todo code, checked can be true or false that will depend on props:

componentWillMount() {
  this.setState({ checked: this.props.checked })
}
// render() { ...
<input
  checked={this.state.checked}
  onChange={handleSelectedTodo}
  type="checkbox"
  value={id}
></input>

Checking on the checkbox updates the parent component state but the checkbox on child is not checked. help?

Body:
This code can also be written this way:-

_handleSelectedTodo(e) {
  e.preventDefault();
  this.setState({checkedIds: [...this.state.checkedIds, e.target.value]});
}
render () { ...
<ul>
{todos.map((todo,todoIndex) => {
  let isChecked = (this.state.checkedIds.indexOf(todo.id) >= 0);
  return (
     <Todo
       key={todo.id}
       {...todo} // pass all the todo property
       onClick={(id) => onTodoClick(todo.id)} //This event should be binded to 'this' inside the constructor
       onTrashClick={(todoIndex) => onDeleteClick(todoIndex)}
       handleSelectedTodo = {this._handleSelectedTodo}
       checked={isChecked}
     />
  )
 });
}

This child component should depend on it's parent state for it's checked property

<input
  checked={this.props.checked}
  onChange={handleSelectedTodo}
  type="checkbox"
  value={id}
></input>

If you want to keep the checked property of child as a state of child as well, then what Mayank said about componentWillReceiveProps would be the right approach.


问:
Jquery Datepicker on Repeating Fields
I know this question has been asked before, but I can't seem to get previous answers to work as my code is a bit different.

So I have a repeating field that I am trying to use datepicker on.  The first instance works fine, if I add a line however, the datepicker displays on another part of the screen and does not enter any information into the field when clicked.

Here is my code:

```<code><script>
jQuery(document).ready(function($) {
    $('.metabox_submit').click(function(e) {
        e.preventDefault();
        $('#publish').click();
    });
    $('#add-row').on('click', function() {
        var row = $('.empty-row.screen-reader-text').clone(true);
        row.removeClass('empty-row screen-reader-text');
        row.insertBefore('#repeatable-fieldset-one tbody>tr:last');
        return false;
    });
    $('.remove-row').on('click', function() {
        $(this).parents('tr').remove();
        return false;
    });
    $('#repeatable-fieldset-one tbody').sortable({
        opacity: 0.6,
        revert: true,
        cursor: 'move',
        handle: '.sort'
    });

    $('.session-time').timepicker({
        'minTime': '8:00am',
        'maxTime': '10:0pm',
        'step': 15,
    });

    $('.session-date').each(function() {
        $(this).datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'mm-dd-yy',
        yearRange: '2017:2020'
        });
    });
});
</script>

});
</script>
<div class="wrap">
<table id="repeatable-fieldset-one" class="form-table">
    <thead>
        <tr>
            <th>Remove</th>
            <th>Session Date</th>
            <th>Session Time</th>
            <th>Sort</th>
        </tr>
    </thead>
    <tbody>

    <?php
    if ( $repeatable_fields ) :
        foreach ( $repeatable_fields as $field ) : // there are complete fields
    ?>
        <tr>
            <td><a class="button remove-row" href="#">-</a></td>
            <td><input type="text" class="session-date" name="session_date[]" value="<?php if($field['session_date'] != '') echo esc_attr( $field['session_date'] ); ?>" /></td>
            <td><input type="text" class="session-time" name="session_time[]" value="<?php if($field['session_time'] != '') echo esc_attr( $field['session_time'] ); ?>" /></td>
            <td><a class="sort">|||</a></td>
        </tr>

    <?php endforeach;
        else : // show a blank one ?>

        <tr>
            <td><a class="button remove-row" href="#">-</a></td>
            <td><input type="text" class="session-date" name="session_date[]" /></td>
            <td><input type="text" class="session-time" name="session_time[]" /></td>
            <td><a class="sort">|||</a></td>
        </tr>

    <?php endif; ?>
    <!-- empty hidden one for jQuery -->

        <tr class="empty-row screen-reader-text">
            <td><a class="button remove-row" href="#">-</a></td>
            <td><input type="text" class="session-date" name="session_date[]" /></td>
            <td><input type="text" class="session-time" name="session_time[]" /></td>
            <td><a class="sort">|||</a></td>
        </tr>
    </tbody>
</table>

<p><a id="add-row" class="button" href="#">Add another</a></p>
</div>
</code>```

答:
For anyone else who comes upon this issue, here is the fix that worked for me.  I was able to get this work for datapicker, but not for timepicker.

```<code>$(document).on('focus', '.session-date', function() {
    $(this).datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'mm-dd-yy',
        yearRange: '2017:2020
    });
});
</code>```

Just use the code in place of

```<code>$('.session-date').each(function() {
    $(this).datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'mm-dd-yy',
        yearRange: '2017:2020'
    });
});
</code>```

Title: Jquery Datepicker on Repeating Fields

Body:
I know this question has been asked before, but I can't seem to get previous answers to work as my code is a bit different.

So I have a repeating field that I am trying to use datepicker on.  The first instance works fine, if I add a line however, the datepicker displays on another part of the screen and does not enter any information into the field when clicked.

Here is my code:

});
</script>

            Remove
            Session Date
            Session Time
            Sort

    <?php
    if ( $repeatable_fields ) :
        foreach ( $repeatable_fields as $field ) : // there are complete fields
    ?>

            -
            <input type="text" class="session-date" name="session_date[]" value="<?php if($field['session_date'] != '') echo esc_attr( $field['session_date'] ); ?>" />
            <input type="text" class="session-time" name="session_time[]" value="<?php if($field['session_time'] != '') echo esc_attr( $field['session_time'] ); ?>" />
            |||

    <?php endforeach;
        else : // show a blank one ?>

            -
            <input type="text" class="session-date" name="session_date[]" />
            <input type="text" class="session-time" name="session_time[]" />
            |||

    <?php endif; ?>

            -
            <input type="text" class="session-date" name="session_date[]" />
            <input type="text" class="session-time" name="session_time[]" />
            |||

Add another

Body:
For anyone else who comes upon this issue, here is the fix that worked for me.  I was able to get this work for datapicker, but not for timepicker.

$(document).on('focus', '.session-date', function() {
    $(this).datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'mm-dd-yy',
        yearRange: '2017:2020
    });
});

Just use the code in place of

$('.session-date').each(function() {
    $(this).datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'mm-dd-yy',
        yearRange: '2017:2020'
    });
});


答:
You failed to call your function inside the main function. One suggestion is to not name the function as main1 and main2 since it is ambiguous.

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

int main1(void)
{
   printf("Came to main1.\n");
}

int main2(void)
{
   printf("Came to main2.\n");
}

int main(void)
{
   printf("Came to main. \n");
   main1();  // this is the plain function call.
   main2();
}
</code>```

Output:

```<code>Came to main.
Came to main1.
Came to main2.
</code>```

More information about the function call.

Title: How to execute main1 when I have main1, main2, and main?

Body:
#include <stdio.h>
#include <string.h>

int main1(void)
{
   printf("Came to main1.\n");
}

int main2(void)
{
   printf("Came to main2.\n");
}

int main(void)
{
   printf("Came to main. \n");
}

I have main1, main2, and main. I want to see main1 output, but every time I execute the program, I can only see main output

Body:
You failed to call your function inside the main function. One suggestion is to not name the function as main1 and main2 since it is ambiguous.

#include <stdio.h>
#include <string.h>

int main1(void)
{
   printf("Came to main1.\n");
}

int main2(void)
{
   printf("Came to main2.\n");
}

int main(void)
{
   printf("Came to main. \n");
   main1();  // this is the plain function call.
   main2();
}

Output:

Came to main.
Came to main1.
Came to main2.

More information about the function call.


问:
Remove quotes between letters
In golang, how can I remove quotes between two letters, like that:

```<code>import (
    "testing"
)

func TestRemoveQuotes(t *testing.T) {
    var a = "bus\"zipcode"
    var mockResult = "bus zipcode"
    a = RemoveQuotes(a)

    if a != mockResult {
        t.Error("Error or TestRemoveQuotes: ", a)
    }
}
</code>```

Function:

```<code>import (
    "fmt"
    "strings"
)

func RemoveQuotes(s string) string {
    s = strings.Replace(s, "\"", "", -1) //here I removed all quotes. I'd like to remove only quotes between letters

    fmt.Println(s)

    return s
}
</code>```

For example:

"bus"zipcode" = "bus zipcode"

答:
I am not sure about what you need when you commented I want to only quote inside test3.

This code is removing the quotes from the inside, as you did, but it is adding the quotes with fmt.Sprintf()

```<code>package main

import (
    "fmt"
    "strings"
)

func main() {
    var a = "\"test1\",\"test2\",\"tes\"t3\""
    fmt.Println(RemoveQuotes(a))
}

func RemoveQuotes(s string) string {
    s = strings.Replace(s, "\"", "", -1) //here I removed all quotes. I'd like to remove only quotes between letters

    return fmt.Sprintf(`"%s"`, s)
}
</code>```

https://play.golang.org/p/dKB9DwYXZp

Title: Remove quotes between letters

Body:
In golang, how can I remove quotes between two letters, like that:

import (
    "testing"
)

func TestRemoveQuotes(t *testing.T) {
    var a = "bus\"zipcode"
    var mockResult = "bus zipcode"
    a = RemoveQuotes(a)

    if a != mockResult {
        t.Error("Error or TestRemoveQuotes: ", a)
    }
}

Function:

import (
    "fmt"
    "strings"
)

func RemoveQuotes(s string) string {
    s = strings.Replace(s, "\"", "", -1) //here I removed all quotes. I'd like to remove only quotes between letters

    fmt.Println(s)

    return s
}

For example:

"bus"zipcode" = "bus zipcode"

Body:
I am not sure about what you need when you commented I want to only quote inside test3.

This code is removing the quotes from the inside, as you did, but it is adding the quotes with fmt.Sprintf()

package main

import (
    "fmt"
    "strings"
)

func main() {
    var a = "\"test1\",\"test2\",\"tes\"t3\""
    fmt.Println(RemoveQuotes(a))
}

func RemoveQuotes(s string) string {
    s = strings.Replace(s, "\"", "", -1) //here I removed all quotes. I'd like to remove only quotes between letters

    return fmt.Sprintf(`"%s"`, s)
}

https://play.golang.org/p/dKB9DwYXZp


问:
How do I get raw phonetics data with System.Speech in C#?
I would like to know how to get the raw phonetic data from System.Speech in C#.

World or sentence recognition work great, but it's "interpreted"
to give a coherent and grammatically correct sentence.
I don't want that; I am looking for a way to get just the translation of audio to phonetics, without interpretation.

答:
I have found what I was looking for here: Speech to Phoneme in .Net

There is a pronunciation argument for the grammar that can be used with dictation mode:

```<code>new DictationGrammar("grammar:dictation#pronunciation");
</code>```

Body:
I have found what I was looking for here: Speech to Phoneme in .Net

There is a pronunciation argument for the grammar that can be used with dictation mode:

new DictationGrammar("grammar:dictation#pronunciation");


问:
How to write to an abstract property in Python 3.4+
In Python 3.6, Let's say I have an abstract class MyAbstractClass

```<code>from abc import ABC, abstractmethod

class MyAbstractClass(ABC):

    @property
    @abstractmethod
    def myProperty(self):
        pass
</code>```

and a class MyInstantiatableClass inherit from it. So how do I write to the property myProperty on instantiation of an object from this class? I'd like to be able to both set and get myProperty. Below doesn't work.

```<code>from MyAbstractClass import MyAbstractClass

class MyInstantiatableClass(MyAbstractClass):
    def __init__(self, desiredValueOfMyProperty):
        ????

    @myProperty.setter
    def myProperty(self, desiredValueOfMyProperty): # value coming from __init__
        self._myProperty = desiredValueOfMyProperty
</code>```

And a main function, say,

```<code>from MyInstantiatableClass import MyInstantiatableClass

def main():
    MyInstantiatableClass(3) # 3 is the desiredValueOfMyProperty for this instantiation
    MyInstantiatableClass(5) # 5 is the desiredValueOfMyProperty for this instantiation
</code>```

答:
It seems there's a discrepancy here; using @property along with @abstractmethod doesn't seem to enforce classes that inherit from your abc to need to define both setter and getter. Using this:

```<code>@property
@abstractmethod
def myProperty(self):
    pass

@myProperty.setter
@abstractmethod
def myProperty(self):
    pass
</code>```

and then providing an implementation only for the getter in the class works and allows for instantiation:

```<code>@property
def myProperty(self):
    return self._myProperty
</code>```

This is due to the fact that only one name (myProperty) appears in the namespace of the ABC, when you override in the base class, you only need to define this one name.

There's a way around that enforces it. You can create separate abstract methods and pass them on to property directly:

```<code>class MyAbstractClass(ABC):

    @abstractmethod
    def getProperty(self):
        pass

    @abstractmethod
    def setProperty(self, val):
        pass

    myAbstractProperty = property(getProperty, setProperty)
</code>```

Providing an implementation for this abc now requires both getter and setter to have an implementation (both names that have been listed as abstractmethods in MyAbstractClass namespace need to have an implementation):

```<code>class MyInstantiatableClass(MyAbstractClass):

    def getProperty(self):
        return self._Property

    def setProperty(self, val):
        self._Property = val
    myAbstractProperty = property(getProperty, setProperty)
</code>```

Implementing them is exactly the same as any old property. There's no difference there.

Body:
In Python 3.6, Let's say I have an abstract class MyAbstractClass

from abc import ABC, abstractmethod

class MyAbstractClass(ABC):

    @property
    @abstractmethod
    def myProperty(self):
        pass

and a class MyInstantiatableClass inherit from it. So how do I write to the property myProperty on instantiation of an object from this class? I'd like to be able to both set and get myProperty. Below doesn't work.

from MyAbstractClass import MyAbstractClass

class MyInstantiatableClass(MyAbstractClass):
    def __init__(self, desiredValueOfMyProperty):
        ????

    @myProperty.setter
    def myProperty(self, desiredValueOfMyProperty): # value coming from __init__
        self._myProperty = desiredValueOfMyProperty

And a main function, say,

from MyInstantiatableClass import MyInstantiatableClass

def main():
    MyInstantiatableClass(3) # 3 is the desiredValueOfMyProperty for this instantiation
    MyInstantiatableClass(5) # 5 is the desiredValueOfMyProperty for this instantiation

Body:
It seems there's a discrepancy here; using @property along with @abstractmethod doesn't seem to enforce classes that inherit from your abc to need to define both setter and getter. Using this:

@property
@abstractmethod
def myProperty(self):
    pass

@myProperty.setter
@abstractmethod
def myProperty(self):
    pass

and then providing an implementation only for the getter in the class works and allows for instantiation:

@property
def myProperty(self):
    return self._myProperty

This is due to the fact that only one name (myProperty) appears in the namespace of the ABC, when you override in the base class, you only need to define this one name.

There's a way around that enforces it. You can create separate abstract methods and pass them on to property directly:

class MyAbstractClass(ABC):

    @abstractmethod
    def getProperty(self):
        pass

    @abstractmethod
    def setProperty(self, val):
        pass

    myAbstractProperty = property(getProperty, setProperty)

Providing an implementation for this abc now requires both getter and setter to have an implementation (both names that have been listed as abstractmethods in MyAbstractClass namespace need to have an implementation):

class MyInstantiatableClass(MyAbstractClass):

    def getProperty(self):
        return self._Property

    def setProperty(self, val):
        self._Property = val
    myAbstractProperty = property(getProperty, setProperty)

Implementing them is exactly the same as any old property. There's no difference there.


问:
how to get only two number after decimal
i have money field in sql table when i m extracting record by table and binding it to datagrid it show money as well 100.0000 four character from decimal i need only two .
Plz suggest.</p>

答:
```<code>select cast(round(123.4321,2) as decimal(18,2))
</code>```

is also a solution for your problem.

Body:
select cast(round(123.4321,2) as decimal(18,2))

is also a solution for your problem.


问:
How would I display my UI
I'm attempting to display my UI by calling the method from my clicker class to my main class.
Main class

```<code>package me.removed.clicker;

import me.removed.clicker.Clicker;

public class Main
{
      public static void main(String[] args)
      {
        Clicker.getClicker().openUI();
      }
    }
</code>```

Clicker class

```<code>package me.removed.clicker;

import java.awt.EventQueue;
import java.awt.Robot;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.FloatControl.Type;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import me.removed.clicker.handler.KeyboardHandler;
import me.removed.clicker.handler.MouseHandler;
import me.removed.clicker.util.Time;
import org.jnativehook.GlobalScreen;

public class Clicker
{
  public static Clicker instance;
  private boolean LEFT_held;
  private boolean LEFT_skip;
  private Time LEFT_pressTime;
  private boolean toggled;
  private Random random;
  private ClickerFrame clickerFrame;
  private MouseHandler clickerHandler;
  private KeyboardHandler keyHandler;
  private Robot robot;
  private Thread thread;

  public boolean isToggled()
  {
    return this.toggled;
  }

  public void setToggled(boolean toggled)
  {
    this.toggled = toggled;
  }

  public Clicker()
  {
    this.LEFT_held = false;
    this.LEFT_skip = false;
    this.toggled = false;
    this.random = new Random();
    try
    {
      GlobalScreen.registerNativeHook();
      this.clickerHandler = new MouseHandler();
      this.keyHandler = new KeyboardHandler();
      GlobalScreen.addNativeMouseListener(this.clickerHandler);
      GlobalScreen.addNativeKeyListener(this.keyHandler);
      this.robot = new Robot();
      LogManager.getLogManager().reset();
      Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
      logger.setLevel(Level.OFF);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    this.thread = new Thread(new Runnable()
    {
      public void run()
      {
        try
        {
          for (;;)
          {
            Thread.sleep(1L);
            if ((Clicker.this.isToggled()) &&

              (Clicker.this.isLeftHeld()))
            {
              long CPSDelay = Clicker.this.generateCPSDelay();
              if (Clicker.this.getLeftPressTime() != null)
              {
                if (Clicker.this.getLeftPressTime().hasPassed())
                {
                  Clicker.this.setLeftPressTime(new Time(CPSDelay));
                  Clicker.this.setLeftSkip(true);
                  Clicker.this.robot.mousePress(16);
                  Clicker.this.robot.mouseRelease(16);

                  Thread runThread = new Thread(new Runnable()
                  {
                    public void run()
                    {
                      try
                      {
                        AudioInputStream audioInputStream =
                          AudioSystem.getAudioInputStream(Clicker.class.getClassLoader().getResource("left_click.wav"));

                        Clip clip = AudioSystem.getClip();

                        clip.open(audioInputStream);

                        float volume = -9.0F - Clicker.this.random.nextFloat() * 11.0F;

                        FloatControl gainControl =
                          (FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN);
                        gainControl.setValue(volume);

                        clip.start();
                      }
                      catch (Exception localException) {}
                    }
                  });
                  runThread.start();
                }
              }
              else
              {
                Clicker.this.setLeftPressTime(new Time(CPSDelay));
                Clicker.this.setLeftSkip(true);
              }
            }
          }
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
      }
    });
    this.thread.start();
  }

  public boolean isLeftHeld()
  {
    return this.LEFT_held;
  }

  public void setLeftHeld(boolean LEFT_held)
  {
    this.LEFT_held = LEFT_held;
  }

  public void destroy()
  {
    try
    {

    }
    catch (Throwable e)
    {
      e.printStackTrace();
    }
    System.exit(0);
  }

  public void openUI()
  {
    EventQueue.invokeLater(new Runnable()
    {
      public void run()
      {
        try
        {
          UIManager.LookAndFeelInfo[] installedLookAndFeels;
          int length = (installedLookAndFeels = UIManager.getInstalledLookAndFeels()).length;
          for (int i = 0; i < length; i++)
          {
            UIManager.LookAndFeelInfo info = installedLookAndFeels[i];
            if ("Windows".equals(info.getName()))
            {
              UIManager.setLookAndFeel(info.getClassName());
              break;
            }
          }
          Clicker.this.clickerFrame = new ClickerFrame();
          Clicker.this.clickerFrame.setVisible(true);
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
      }
    });
  }

  public boolean getLeftSkip()
  {
    return this.LEFT_skip;
  }

  public void setLeftSkip(boolean LEFT_skip)
  {
    this.LEFT_skip = LEFT_skip;
  }

  public Time getLeftPressTime()
  {
    return this.LEFT_pressTime;
  }

  public void setLeftPressTime(Time LEFT_pressTime)
  {
    this.LEFT_pressTime = LEFT_pressTime;
  }

  public ClickerFrame getClickerFrame()
  {
    return this.clickerFrame;
  }

  public long generateCPSDelay()
  {
    int minCPS = 12;
    int maxCPS = 15;
    double minDiff = 83.0D;
    double maxDiff = 66.0D;
    double randomDiff = this.random.nextDouble() * 17.0D;
    return (long) (66.0D + randomDiff);
  }

  public static void setupClicker()
  {
    (Clicker.instance = new Clicker()).openUI();
  }

  public static Clicker getClicker()
  {
    return instance;
  }
}
</code>```

You can see in my main class I attempted to call OpenUI however even when I do this nothing happens, the process runs but no UI opens, I tried removing Void also to no avail as shown in other posts.

CONSOLE ERRORS:

```<code>Jun 06, 2017 3:43:54 AM org.jnativehook.DefaultLibraryLocator getLibraries
INFO: Library extracted successfully: C:\Users\WarDev\AppData\Local\Temp\JNativeHook-2.0.3.dll (0x7432773EB4D09DC286D43FCC77DDB0E1E3BCE2B4).

Jun 06, 2017 3:43:54 AM java.lang.ClassLoader$NativeLibrary load
INFO: hook_get_auto_repeat_rate [42]: SPI_GETKEYBOARDSPEED: 31.

Jun 06, 2017 3:43:54 AM java.lang.ClassLoader$NativeLibrary load
INFO: hook_get_auto_repeat_delay [56]: SPI_GETKEYBOARDDELAY: 1.

Jun 06, 2017 3:43:54 AM java.lang.ClassLoader$NativeLibrary load
INFO: hook_get_pointer_acceleration_multiplier [70]: SPI_GETMOUSE[2]: 1.

Jun 06, 2017 3:43:54 AM java.lang.ClassLoader$NativeLibrary load
INFO: hook_get_pointer_acceleration_threshold [84]: SPI_GETMOUSE[0]: 6.

Jun 06, 2017 3:43:54 AM java.lang.ClassLoader$NativeLibrary load
INFO: hook_get_pointer_acceleration_threshold [86]: SPI_GETMOUSE[1]: 10.

Jun 06, 2017 3:43:55 AM java.lang.ClassLoader$NativeLibrary load
INFO: hook_get_pointer_sensitivity [101]: SPI_GETMOUSESPEED: 10.

Jun 06, 2017 3:43:55 AM java.lang.ClassLoader$NativeLibrary load
INFO: hook_get_multi_click_time [115]: GetDoubleClickTime: 500.

java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(Unknown Source)
    at me.dewgs.clicker.ClickerFrame.<init>(ClickerFrame.java:442)
    at me.dewgs.clicker.Clicker$2.run(Clicker.java:175)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
</code>```

答:
```<code>public static Clicker instance;
</code>```

Looks to me like instance is null.

```<code>public static void setupClicker()
  {
    (Clicker.instance = new Clicker()).openUI();
  }
</code>```

Where do you ever invoke setupClicker() to initialize the variable?

Why would you invoke getClicker() when you have the setupClicker() method to display the UI?

Title: How would I display my UI

Body:
I'm attempting to display my UI by calling the method from my clicker class to my main class.
Main class

package me.removed.clicker;

import me.removed.clicker.Clicker;

public class Main
{
      public static void main(String[] args)
      {
        Clicker.getClicker().openUI();
      }
    }

Clicker class

package me.removed.clicker;

import java.awt.EventQueue;
import java.awt.Robot;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.FloatControl.Type;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import me.removed.clicker.handler.KeyboardHandler;
import me.removed.clicker.handler.MouseHandler;
import me.removed.clicker.util.Time;
import org.jnativehook.GlobalScreen;

public class Clicker
{
  public static Clicker instance;
  private boolean LEFT_held;
  private boolean LEFT_skip;
  private Time LEFT_pressTime;
  private boolean toggled;
  private Random random;
  private ClickerFrame clickerFrame;
  private MouseHandler clickerHandler;
  private KeyboardHandler keyHandler;
  private Robot robot;
  private Thread thread;

  public boolean isToggled()
  {
    return this.toggled;
  }

  public void setToggled(boolean toggled)
  {
    this.toggled = toggled;
  }

  public Clicker()
  {
    this.LEFT_held = false;
    this.LEFT_skip = false;
    this.toggled = false;
    this.random = new Random();
    try
    {
      GlobalScreen.registerNativeHook();
      this.clickerHandler = new MouseHandler();
      this.keyHandler = new KeyboardHandler();
      GlobalScreen.addNativeMouseListener(this.clickerHandler);
      GlobalScreen.addNativeKeyListener(this.keyHandler);
      this.robot = new Robot();
      LogManager.getLogManager().reset();
      Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
      logger.setLevel(Level.OFF);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    this.thread = new Thread(new Runnable()
    {
      public void run()
      {
        try
        {
          for (;;)
          {
            Thread.sleep(1L);
            if ((Clicker.this.isToggled()) &&

              (Clicker.this.isLeftHeld()))
            {
              long CPSDelay = Clicker.this.generateCPSDelay();
              if (Clicker.this.getLeftPressTime() != null)
              {
                if (Clicker.this.getLeftPressTime().hasPassed())
                {
                  Clicker.this.setLeftPressTime(new Time(CPSDelay));
                  Clicker.this.setLeftSkip(true);
                  Clicker.this.robot.mousePress(16);
                  Clicker.this.robot.mouseRelease(16);

                  Thread runThread = new Thread(new Runnable()
                  {
                    public void run()
                    {
                      try
                      {
                        AudioInputStream audioInputStream =
                          AudioSystem.getAudioInputStream(Clicker.class.getClassLoader().getResource("left_click.wav"));

                        Clip clip = AudioSystem.getClip();

                        clip.open(audioInputStream);

                        float volume = -9.0F - Clicker.this.random.nextFloat() * 11.0F;

                        FloatControl gainControl =
                          (FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN);
                        gainControl.setValue(volume);

                        clip.start();
                      }
                      catch (Exception localException) {}
                    }
                  });
                  runThread.start();
                }
              }
              else
              {
                Clicker.this.setLeftPressTime(new Time(CPSDelay));
                Clicker.this.setLeftSkip(true);
              }
            }
          }
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
      }
    });
    this.thread.start();
  }

  public boolean isLeftHeld()
  {
    return this.LEFT_held;
  }

  public void setLeftHeld(boolean LEFT_held)
  {
    this.LEFT_held = LEFT_held;
  }

  public void destroy()
  {
    try
    {

    }
    catch (Throwable e)
    {
      e.printStackTrace();
    }
    System.exit(0);
  }

  public void openUI()
  {
    EventQueue.invokeLater(new Runnable()
    {
      public void run()
      {
        try
        {
          UIManager.LookAndFeelInfo[] installedLookAndFeels;
          int length = (installedLookAndFeels = UIManager.getInstalledLookAndFeels()).length;
          for (int i = 0; i < length; i++)
          {
            UIManager.LookAndFeelInfo info = installedLookAndFeels[i];
            if ("Windows".equals(info.getName()))
            {
              UIManager.setLookAndFeel(info.getClassName());
              break;
            }
          }
          Clicker.this.clickerFrame = new ClickerFrame();
          Clicker.this.clickerFrame.setVisible(true);
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
      }
    });
  }

  public boolean getLeftSkip()
  {
    return this.LEFT_skip;
  }

  public void setLeftSkip(boolean LEFT_skip)
  {
    this.LEFT_skip = LEFT_skip;
  }

  public Time getLeftPressTime()
  {
    return this.LEFT_pressTime;
  }

  public void setLeftPressTime(Time LEFT_pressTime)
  {
    this.LEFT_pressTime = LEFT_pressTime;
  }

  public ClickerFrame getClickerFrame()
  {
    return this.clickerFrame;
  }

  public long generateCPSDelay()
  {
    int minCPS = 12;
    int maxCPS = 15;
    double minDiff = 83.0D;
    double maxDiff = 66.0D;
    double randomDiff = this.random.nextDouble() * 17.0D;
    return (long) (66.0D + randomDiff);
  }

  public static void setupClicker()
  {
    (Clicker.instance = new Clicker()).openUI();
  }

  public static Clicker getClicker()
  {
    return instance;
  }
}

You can see in my main class I attempted to call OpenUI however even when I do this nothing happens, the process runs but no UI opens, I tried removing Void also to no avail as shown in other posts.

CONSOLE ERRORS:

Jun 06, 2017 3:43:54 AM org.jnativehook.DefaultLibraryLocator getLibraries
INFO: Library extracted successfully: C:\Users\WarDev\AppData\Local\Temp\JNativeHook-2.0.3.dll (0x7432773EB4D09DC286D43FCC77DDB0E1E3BCE2B4).

Jun 06, 2017 3:43:54 AM java.lang.ClassLoader$NativeLibrary load
INFO: hook_get_auto_repeat_rate [42]: SPI_GETKEYBOARDSPEED: 31.

Jun 06, 2017 3:43:54 AM java.lang.ClassLoader$NativeLibrary load
INFO: hook_get_auto_repeat_delay [56]: SPI_GETKEYBOARDDELAY: 1.

Jun 06, 2017 3:43:54 AM java.lang.ClassLoader$NativeLibrary load
INFO: hook_get_pointer_acceleration_multiplier [70]: SPI_GETMOUSE[2]: 1.

Jun 06, 2017 3:43:54 AM java.lang.ClassLoader$NativeLibrary load
INFO: hook_get_pointer_acceleration_threshold [84]: SPI_GETMOUSE[0]: 6.

Jun 06, 2017 3:43:54 AM java.lang.ClassLoader$NativeLibrary load
INFO: hook_get_pointer_acceleration_threshold [86]: SPI_GETMOUSE[1]: 10.

Jun 06, 2017 3:43:55 AM java.lang.ClassLoader$NativeLibrary load
INFO: hook_get_pointer_sensitivity [101]: SPI_GETMOUSESPEED: 10.

Jun 06, 2017 3:43:55 AM java.lang.ClassLoader$NativeLibrary load
INFO: hook_get_multi_click_time [115]: GetDoubleClickTime: 500.

java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(Unknown Source)
    at me.dewgs.clicker.ClickerFrame.<init>(ClickerFrame.java:442)
    at me.dewgs.clicker.Clicker$2.run(Clicker.java:175)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

Body:
public static Clicker instance;

Looks to me like instance is null.

public static void setupClicker()
  {
    (Clicker.instance = new Clicker()).openUI();
  }

Where do you ever invoke setupClicker() to initialize the variable?

Why would you invoke getClicker() when you have the setupClicker() method to display the UI?


问:
Using checkbox to perform print action
I'm creating a database for a preventative maintenance program for the equipment in my facility. We have about 70 different machines with individuals preventative maintenance instructions, and I've been able to create tables for machines with the instructions attached to them by using forms that will update the database.

I created a main form that will filter which PM needs to be done based on the date that is searched that will filter through the machines in the database, access does this fine. The problem I'm currently having trouble with is finding a way to add checkboxes to this main form, and print off only the ones that are selected with a button. The plan we have is to have the mechanics to be able to print off the PM instructions, and use the print off to update the database. Is there a way this can be done with checkboxes or optionboxes?

Here's a picture of form without an checkboxes in it.

Here's a picture of the form view of where the user will input information that will update the database. WE're trying to get this to print out by using checkbox in the form that will search for the PM instruction

答: I think this is definitely doable - IMHO it would be a combination of setting the click event in the boxes to contain code explicitly stating PrintOut functions specific to the pages you want to print out given a specific box ticked.</p>

Title: Using checkbox to perform print action


问:
How do I do this in MATLAB?
I have a string s that's composed of random symbols and numbers that user types in.

Each letter ( uppercase or lowercase ) should be repeated the number of times indicated by the following digit.

```<code>%% 'x234'   - 'xx34'
%% 'xx3333' - 'xxxx333' etc.

s = 'M2ab34*y2'
</code>```

string s1 should be:

```<code>s1='MMabbb4*yy'
</code>```

I hope you get my point.

答:
You can do this using regexprep:

```<code>s = 'M2ab34*y2';
s1 = regexprep(s, '(\D)(\d)', '${repmat($1, [1 str2double($2)])}')

s1 =

MMabbb4*yy
</code>```

The '(\D)(\d)' will match a single non-numeric digit character followed by a single numeric digit character. Each character is captured in a token and subsequently passed to a dynamic expression for the replacement string (which uses repmat and str2double to replicate the character).

If you only want letters to be replicated (not symbols like *), you can use '([a-zA-Z])(\d)' for the match expression.

Title: How do I do this in MATLAB?

Body:
I have a string s that's composed of random symbols and numbers that user types in.

Each letter ( uppercase or lowercase ) should be repeated the number of times indicated by the following digit.

%% 'x234'   - 'xx34'
%% 'xx3333' - 'xxxx333' etc.

s = 'M2ab34*y2'

string s1 should be:

s1='MMabbb4*yy'

I hope you get my point.

Body:
You can do this using regexprep:

s = 'M2ab34*y2';
s1 = regexprep(s, '(\D)(\d)', '${repmat($1, [1 str2double($2)])}')

s1 =

MMabbb4*yy

The '(\D)(\d)' will match a single non-numeric digit character followed by a single numeric digit character. Each character is captured in a token and subsequently passed to a dynamic expression for the replacement string (which uses repmat and str2double to replicate the character).

If you only want letters to be replicated (not symbols like *), you can use '([a-zA-Z])(\d)' for the match expression.