问:
Get current node of a pod in Kubernetes source code
I am doing with Kubernetes.

Now, I am doing with leaderelection in K8S.

Because I want to develop something here. So, I need to get the node which current pod belongs to.

For example,in this file leaderelection.go, after a pod becomes leader, I want to know which node this pod belongs to.

Can someone help me? Can you give me an example of code!

Thank you!

答:
First of all the codebase you are referring to is outdated.

You can use kubernetes/client-go library to query Kubernetes API. Refer to examples

Just a minimal code:

```<code>  pod, - := ks.clientSet.CoreV1().Pods(apiV1.NamespaceDefault).Get("your_pod_name", metaV1.GetOptions{})
  fmt.Printf("node name: %s", pod.Spec.NodeName)
</code>```

Body:
First of all the codebase you are referring to is outdated.

You can use kubernetes/client-go library to query Kubernetes API. Refer to examples

Just a minimal code:

  pod, - := ks.clientSet.CoreV1().Pods(apiV1.NamespaceDefault).Get("your_pod_name", metaV1.GetOptions{})
  fmt.Printf("node name: %s", pod.Spec.NodeName)


来源: stackexchange

问:
How to Convince management to upgrade to .Net 4.0
We developed an application using .net 2.0.
We license our software which means whenever we release a new version, we have to push out the change to all our existing clients.

No one in my group has the slightest motivation to upgrade to a newer version of .net. They simple see it as more work for our support team to deploy and argue that clients will be resistant to any change.

Can anyone point me in the direction of some argument i could present to Non programmers that might sway them.

If noting else, some argument that it is safe, and will not cause our clients any harm who already have the .net 2.0 framework on their machines?

I figure it's hopeless. I'm gonna be stuck using the .net 2.0 framework until for another 4 or 5 years i bet... perhaps longer :( help!

I really want to be able to use WCF, LINQ, WPF (possible), and the option to use the Entity Framework 4.0.!

thanks

jonathan

答:
So your real motivation is

"I really want to be able to use WCF, LINQ, WPF (possible), and the option to use the Entity Framework 4.0.!"

This is not a good enough reason for upgrading! If you can't convince yourself that the company is going to get more profits, don't try to convince the management.

Sometimes there is no reason to upgrade, and it may be even a wrong business move. Consider your business case if you want to convince managers.

ContentLicense: CC BY-SA 3.0


问:
If I have inputs in shape (32,256,256,3) and I want to create a custom loss function replicating the following equation in Keras
Create custom Loss function in keras for y_pred and y_loss of shape (32,256,256,3) where 32 is the batch_size and 3 is the number of channels of the image of dimention 256x256 and the loss equation:

It is given in this paper, the loss function for Surface Normals: https://arxiv.org/pdf/1411.4734.pdf

```<code>def normal_loss_1 (y_true, y_pred):
    y_true_flat = K.flatten(y_true)
    y_pred_flat = K.flatten(y_pred)
    #d = y_pred_flat * y_true_flat
    d = np.dot(y_pred_flat,y_true_flat)
    y_sum = K.sum(d)
    n_pixels = 256 * 256
    normal_output = y_sum/n_pixels
    normal_output = tf.reduce_mean(normal_output)
    return -normal_output
</code>```

I do not get any error with this but the result is not as expected. Is there any other and better way to write the code? Any help will be appreciated. Thank you in advance!

答:
You are using numpy to get dot product of tensors. Here y_true_flat and y_pred_flat are tensors. You should either use tensorflow.tensordot method or tensorflow.keras.backend.dot method to get product of two tensors. Since these tensors are vectors, tensorflow.matmul could also work.

def normal_loss_1 (y_true, y_pred):
    dim = tf.reduce_prod(tf.shape(y_true)[1:])
    y_true_flatten = tf.reshape(y_true, [-1, dim])
    y_pred_flatten = tf.reshape(y_pred, [-1, dim])
    d = tf.tensordot(y_pred_flatten,y_true_flatten, 1)
    y_sum = tf.reduce_sum(d, 1)
    n_pixels = 256 * 256
    normal_output = y_sum/n_pixels
    normal_output = tf.reduce_mean(normal_output)
    return -normal_output
```

Edit

K.flatten will convert the tensors(y_true and y_pred) into vectors and the batch dimension will disappear. This means you cannot average the loss over the batch.

ContentLicense: CC BY-SA 4.0

Body:
Create custom Loss function in keras for y_pred and y_loss of shape (32,256,256,3) where 32 is the batch_size and 3 is the number of channels of the image of dimention 256x256 and the loss equation:

It is given in this paper, the loss function for Surface Normals: https://arxiv.org/pdf/1411.4734.pdf

def normal_loss_1 (y_true, y_pred):
    y_true_flat = K.flatten(y_true)
    y_pred_flat = K.flatten(y_pred)
    #d = y_pred_flat * y_true_flat
    d = np.dot(y_pred_flat,y_true_flat)
    y_sum = K.sum(d)
    n_pixels = 256 * 256
    normal_output = y_sum/n_pixels
    normal_output = tf.reduce_mean(normal_output)
    return -normal_output

I do not get any error with this but the result is not as expected. Is there any other and better way to write the code? Any help will be appreciated. Thank you in advance!

Body:
You are using numpy to get dot product of tensors. Here y_true_flat and y_pred_flat are tensors. You should either use tensorflow.tensordot method or tensorflow.keras.backend.dot method to get product of two tensors. Since these tensors are vectors, tensorflow.matmul could also work.

def normal_loss_1 (y_true, y_pred):
    dim = tf.reduce_prod(tf.shape(y_true)[1:])
    y_true_flatten = tf.reshape(y_true, [-1, dim])
    y_pred_flatten = tf.reshape(y_pred, [-1, dim])
    d = tf.tensordot(y_pred_flatten,y_true_flatten, 1)
    y_sum = tf.reduce_sum(d, 1)
    n_pixels = 256 * 256
    normal_output = y_sum/n_pixels
    normal_output = tf.reduce_mean(normal_output)
    return -normal_output

Edit

K.flatten will convert the tensors(y_true and y_pred) into vectors and the batch dimension will disappear. This means you cannot average the loss over the batch.


问:
Confusing about Kotlin Coroutines execution: where to call await()?
I read a lot of docs about Kotlin coroutines but still having some doubts. I'm using Retrofit with coroutines so I need to do request with Dispatchers.IO context but use result within Dispatchers.Main context to assign it to ViewModel. My code is:</p>

```<code>fun doHttpreq() {
    viewModelScope.launch(Dispatchers.IO) {
        try {
            //should I call await() here? (I guess the correct way to keep execution of request outside of Main thread)
            val request = RestClient.instance.getItems().await()

            withContext(Dispatchers.Main) {
                //or should I call await() here? (BUT need request to be executed outside of Main thread!)

                if (request.isSuccessful) {
                   //asign items to ViewModel

                } else {
                    //asign error to ViewModel
                }
            }

        } catch (e: Exception) {
            withContext(Dispatchers.Main) {
                //asign error to ViewModel
            }
        }
    }
}
</code>```

答:
You can take your deffered job in variable and then await it on your Main dispatcher like below :

```<code>try {
        //Rather than await here, you take your Job as Deffered
        val request: Deferred? = RestClient.instance.getItems()

        withContext(Dispatchers.Main) {
            //Yes, you can await here because it's non-blocking call and can be safely obtained from here once completed
            val result = request?.await()
            if (request.isSuccessful) {
               //asign items to ViewModel

            } else {
                //asign error to ViewModel
            }
        }

    } catch (e: Exception) {
        withContext(Dispatchers.Main) {
            //asign error to ViewModel
        }
    }
</code>```

What official doc states about await() :

Awaits for completion of this value without blocking a thread and resumes when deferred computation is complete, returning the resulting value or throwing the corresponding exception if the deferred was cancelled.

This suspending function is cancellable. If the Job of the current coroutine is cancelled or completed while this suspending function is waiting, this function immediately resumes with CancellationException.

This function can be used in select invocation with onAwait clause. Use isCompleted to check for completion of this deferred value without waiting.

Body:
I read a lot of docs about Kotlin coroutines but still having some doubts. I'm using Retrofit with coroutines so I need to do request with Dispatchers.IO context but use result within Dispatchers.Main context to assign it to ViewModel. My code is:

fun doHttpreq() {
    viewModelScope.launch(Dispatchers.IO) {
        try {
            //should I call await() here? (I guess the correct way to keep execution of request outside of Main thread)
            val request = RestClient.instance.getItems().await()

            withContext(Dispatchers.Main) {
                //or should I call await() here? (BUT need request to be executed outside of Main thread!)

                if (request.isSuccessful) {
                   //asign items to ViewModel

                } else {
                    //asign error to ViewModel
                }
            }

        } catch (e: Exception) {
            withContext(Dispatchers.Main) {
                //asign error to ViewModel
            }
        }
    }
}

Body:
You can take your deffered job in variable and then await it on your Main dispatcher like below :

try {
        //Rather than await here, you take your Job as Deffered
        val request: Deferred? = RestClient.instance.getItems()

        withContext(Dispatchers.Main) {
            //Yes, you can await here because it's non-blocking call and can be safely obtained from here once completed
            val result = request?.await()
            if (request.isSuccessful) {
               //asign items to ViewModel

            } else {
                //asign error to ViewModel
            }
        }

    } catch (e: Exception) {
        withContext(Dispatchers.Main) {
            //asign error to ViewModel
        }
    }

What official doc states about await() :

Awaits for completion of this value without blocking a thread and resumes when deferred computation is complete, returning the resulting value or throwing the corresponding exception if the deferred was cancelled.

This suspending function is cancellable. If the Job of the current coroutine is cancelled or completed while this suspending function is waiting, this function immediately resumes with CancellationException.

This function can be used in select invocation with onAwait clause. Use isCompleted to check for completion of this deferred value without waiting.


问:
Menu key as a sticky modkey for Awesome WM
I am considering switching to Awesome WM (for several reasons, hackability being probably the most important - I am a heavy Emacs user;-)).

I used to use a tiling WM (StumpWM) for some time several years ago, and it had a nice feature of binding only one key as a "prefix".  I set it up to be the (otherwise useless for me) "menu" key, so essentially all WM bindings were "press menu, release it, press something else".

From the docs/tutorials I can see that Awesome has a slightly different approach of binding its functions to "modkey+something".

Is it possible to use "menu" as a "sticky modkey" as I was used to?  Or rather, how do I do that?

答:
You could create a "normal" keybinding for the Menu key, start a keygrabber in there and use that to get the "something" that follows. It would mean that you have to reinvent some wheels yourself, because the code in AwesomeWM will not manage keybindings for you, but it should be workable.

Quick example that does not do much to get you started:

```<code>diff --git a/awesomerc.lua b/awesomerc.lua
index 5d2bd2c10..7973b210a 100644
--- a/awesomerc.lua
+++ b/awesomerc.lua
@@ -242,6 +243,12 @@ root.buttons(gears.table.join(
 -- {{{ Key bindings
 -- @DOC_GLOBAL_KEYBINDINGS@
 globalkeys = gears.table.join(
+    awful.key({}, "Menu", nil, function()
+        keygrabber.run(function(mods, key, action)
+            print("You did:", gears.debug.dump_return(mods), key, action)
+            keygrabber.stop()
+        end)
+    end),
     awful.key({ modkey,           }, "s",      hotkeys_popup.show_help,
               {description="show help", group="awesome"}),
     awful.key({ modkey,           }, "Left",   awful.tag.viewprev,
</code>```

What this does is to print the first "keyboard event" after the Menu key was released. This could e.g. be "a key was released that was pressed before the Menu key was released", but you would likely only care about things like "'s' was pressed"...

Body:
You could create a "normal" keybinding for the Menu key, start a keygrabber in there and use that to get the "something" that follows. It would mean that you have to reinvent some wheels yourself, because the code in AwesomeWM will not manage keybindings for you, but it should be workable.

Quick example that does not do much to get you started:

diff --git a/awesomerc.lua b/awesomerc.lua
index 5d2bd2c10..7973b210a 100644
--- a/awesomerc.lua
+++ b/awesomerc.lua
@@ -242,6 +243,12 @@ root.buttons(gears.table.join(
 -- {{{ Key bindings
 -- @DOC_GLOBAL_KEYBINDINGS@
 globalkeys = gears.table.join(
+    awful.key({}, "Menu", nil, function()
+        keygrabber.run(function(mods, key, action)
+            print("You did:", gears.debug.dump_return(mods), key, action)
+            keygrabber.stop()
+        end)
+    end),
     awful.key({ modkey,           }, "s",      hotkeys_popup.show_help,
               {description="show help", group="awesome"}),
     awful.key({ modkey,           }, "Left",   awful.tag.viewprev,

What this does is to print the first "keyboard event" after the Menu key was released. This could e.g. be "a key was released that was pressed before the Menu key was released", but you would likely only care about things like "'s' was pressed"...


问:
Autowiring class in controller, throwing unexpected token '@' in syntax @Autowired
While Trying to autowire a service class to my restcontroller in springboot, it is throwing build error unexpected token @, at @Autowired notation

This is my controller class.

```<code>@RestController
class RestAPIController{

@Autowired
private getTextBooks service

@RequestMapping(value = "/textbooks", method = RequestMethod.GET)
</code>```

Interface for autowiring

```<code>import org.springframework.stereotype.Component

@Component
public interface Books{
    public String getText(String name)

}
</code>```

Class implementing Interface

```<code>@Componet
Class getTextBooks implements Books{
@Override
def getText(String name){
return "Text Book Name is" + name
}
}
</code>```

Unable to Autowire in Controller

答:
Name your class in capital letter like :

```<code>@Componet
Class GetTextBooks implements Books{
 @Override
 def getText(String name){
  return "Text Book Name is" + name
 }
}
</code>```

It's java convention to name class by starting with Capital case letters.

Body:
While Trying to autowire a service class to my restcontroller in springboot, it is throwing build error unexpected token @, at @Autowired notation

This is my controller class.

@RestController
class RestAPIController{

@Autowired
private getTextBooks service

@RequestMapping(value = "/textbooks", method = RequestMethod.GET)

Interface for autowiring

import org.springframework.stereotype.Component

@Component
public interface Books{
    public String getText(String name)

}

Class implementing Interface

@Componet
Class getTextBooks implements Books{
@Override
def getText(String name){
return "Text Book Name is" + name
}
}

Unable to Autowire in Controller

Body:
Name your class in capital letter like :

@Componet
Class GetTextBooks implements Books{
 @Override
 def getText(String name){
  return "Text Book Name is" + name
 }
}

It's java convention to name class by starting with Capital case letters.


问:
Check previous row value to copy data from one column to another
I would like to copy the values from one column (PERSONAL INFORMATION) to the other (VARIABLE) based on multiple conditions as listed below

Check whether 'PERSONAL INFORMATION' column starts with digits

Check whether the corresponding row value in 'VARIABLE' column is Nan

Check whether the previous row value in 'VARIABLE' column is not Nan (Here 'gender' is not nan but there might be cases when it's Nan)

Once all the conditions are met, I would like to copy over the values from 'PERSONAL INFORMATION' COLUMN TO 'VARIABLE' COLUMN

Please find below how the input data looks like

```<code>df = pd.DataFrame({'PERSONAL INFORMATION':['Gender','1.Male','2.Female','Ethnicity','1.Chinese','2.Indian','3.Eurasian','Marital Status','1.Single','2.Married','3.Divorced'], 'VARIABLE':['gender', np.nan, np.nan,'ethn',np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]})
</code>```

Marital status options shouldn't be copied to "Variable" column as the previous row is Nan here.

I was using np.where option but wasn't sure how to check the previous row value. I don't wish to use for loop.

```<code>df['VARIABLE'] = np.where((df['PERSONAL
INFORMATION'].str.startswith(('\d+')) == True) & (df['VARIABLE'].isna() ==
True) & 3RD CONDITION FOR PREVIOUS ROW CHECK
</code>```

Can you please help me to find out how to check the previous row value for nan. If it's Nan i don't wish to copy the data. If it's not Nan, then the data has to be copied

答:
I believe you need Series.str.contains with ^ for start of string and \d for digit, then create groups by testing values not contains digits with Series.cumsum and GroupBy.transform with first:

```<code>m1 = df['PERSONAL INFORMATION'].str.contains('^\d')
s = df.groupby((~m1).cumsum())['VARIABLE'].transform('first')

mask = m1 & df['VARIABLE'].isna() & s.notna()

df.loc[mask, 'VARIABLE'] = df.loc[mask, 'PERSONAL INFORMATION']
print (df)
   PERSONAL INFORMATION    VARIABLE
0                Gender      gender
1                1.Male      1.Male
2              2.Female    2.Female
3             Ethnicity        ethn
4             1.Chinese   1.Chinese
5              2.Indian    2.Indian
6            3.Eurasian  3.Eurasian
7        Marital Status         NaN
8              1.Single         NaN
9             2.Married         NaN
10           3.Divorced         NaN
</code>```

Details:

```<code>print ((~m1).cumsum())
0     1
1     1
2     1
3     2
4     2
5     2
6     2
7     3
8     3
9     3
10    3
Name: PERSONAL INFORMATION, dtype: int32

print (df.groupby((~m1).cumsum())['VARIABLE'].transform('first'))
0     gender
1     gender
2     gender
3       ethn
4       ethn
5       ethn
6       ethn
7        NaN
8        NaN
9        NaN
10       NaN
Name: VARIABLE, dtype: object
</code>```

Body:
I would like to copy the values from one column (PERSONAL INFORMATION) to the other (VARIABLE) based on multiple conditions as listed below

Check whether 'PERSONAL INFORMATION' column starts with digits

Check whether the corresponding row value in 'VARIABLE' column is Nan

Check whether the previous row value in 'VARIABLE' column is not Nan (Here 'gender' is not nan but there might be cases when it's Nan)

Once all the conditions are met, I would like to copy over the values from 'PERSONAL INFORMATION' COLUMN TO 'VARIABLE' COLUMN

Please find below how the input data looks like

df = pd.DataFrame({'PERSONAL INFORMATION':['Gender','1.Male','2.Female','Ethnicity','1.Chinese','2.Indian','3.Eurasian','Marital Status','1.Single','2.Married','3.Divorced'], 'VARIABLE':['gender', np.nan, np.nan,'ethn',np.nan,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]})

Marital status options shouldn't be copied to "Variable" column as the previous row is Nan here.

I was using np.where option but wasn't sure how to check the previous row value. I don't wish to use for loop.

df['VARIABLE'] = np.where((df['PERSONAL
INFORMATION'].str.startswith(('\d+')) == True) & (df['VARIABLE'].isna() ==
True) & 3RD CONDITION FOR PREVIOUS ROW CHECK

Can you please help me to find out how to check the previous row value for nan. If it's Nan i don't wish to copy the data. If it's not Nan, then the data has to be copied

Body:
I believe you need Series.str.contains with ^ for start of string and \d for digit, then create groups by testing values not contains digits with Series.cumsum and GroupBy.transform with first:

m1 = df['PERSONAL INFORMATION'].str.contains('^\d')
s = df.groupby((~m1).cumsum())['VARIABLE'].transform('first')

mask = m1 & df['VARIABLE'].isna() & s.notna()

df.loc[mask, 'VARIABLE'] = df.loc[mask, 'PERSONAL INFORMATION']
print (df)
   PERSONAL INFORMATION    VARIABLE
0                Gender      gender
1                1.Male      1.Male
2              2.Female    2.Female
3             Ethnicity        ethn
4             1.Chinese   1.Chinese
5              2.Indian    2.Indian
6            3.Eurasian  3.Eurasian
7        Marital Status         NaN
8              1.Single         NaN
9             2.Married         NaN
10           3.Divorced         NaN

Details:

print ((~m1).cumsum())
0     1
1     1
2     1
3     2
4     2
5     2
6     2
7     3
8     3
9     3
10    3
Name: PERSONAL INFORMATION, dtype: int32

print (df.groupby((~m1).cumsum())['VARIABLE'].transform('first'))
0     gender
1     gender
2     gender
3       ethn
4       ethn
5       ethn
6       ethn
7        NaN
8        NaN
9        NaN
10       NaN
Name: VARIABLE, dtype: object


问:
Unable to do master-slave setup on AWS instances. When i run jmeter script from master i get an exception
. I am getting below error, firewalls have been disabled on both servers

```<code>Connection refused to host: 10.XX.XX.XXX; nested exception is:
    java.net.ConnectException: Connection refused (Connection refused)
</code>```

I have set below on slave in jmeter.properties

server_port=1099
server.rmi.localport=50000

Master has below setting in jmeter.properties

remote_hosts= slave.ip,master.ip   (as i want to use master as slave as well)
client.rmi.localport=60000

I have generated the rmi_keystore.jks file and placed that on slave server bin folder.

After that i started the slave server to listen by using

```<code>./jmeter-server -Djava.rmi.server.hostname=10.xx.xx.xxx
</code>```

It then starts the slave server.

After that i run the script from master in non-gui mode.

```<code>./jmeter -n -t pathtoscript.jmx -l logfilepath.csv -r
Creating summariser <summary>
Created the tree successfully using pathtoscript.jmx
Configuring remote engine: 10.xx.xx.xxx
Connection refused to host: 10.xx.xx.xxx; nested exception is:
    java.net.ConnectException: Connection refused (Connection refused)
Failed to configure 10.xx.xx.xxx (this is slave ip)
Configuring remote engine: 10.xx.xx.xxx (this is my master ip)
Connection refused to host: 10.xx.xx.xxx; nested exception is:
    java.net.ConnectException: Connection refused (Connection refused)
Failed to configure 10.xx.xx.xxx (this is my master ip)
Stopping remote engines
Remote engines have been stopped
Error in NonGUIDriver java.lang.RuntimeException: Following remote engines could not be configured:[10.xx.xx.xxx, 10.xx.xx.xxx]
</code>```

答:
My issue is resolved.

Slave command:
./jmeter-server -Dserver.rmi.localport=50000 -Dserver_port=1099 -Djava.rmi.server.hostname="Slaveipaddress" -Jserver.rmi.ssl.disable=true

Master command:
./jmeter -n -t script.jmx -RSlaveipaddress -l results.jtl -Jserver.rmi.ssl.disable=true

Also make sure if you have any plugins in script it should be present on both master and slave as well as data file (if reading data from file) should be present on the same location on both master and slave

Body:
. I am getting below error, firewalls have been disabled on both servers

Connection refused to host: 10.XX.XX.XXX; nested exception is:
    java.net.ConnectException: Connection refused (Connection refused)

I have set below on slave in jmeter.properties

server_port=1099
server.rmi.localport=50000

Master has below setting in jmeter.properties

remote_hosts= slave.ip,master.ip   (as i want to use master as slave as well)
client.rmi.localport=60000

I have generated the rmi_keystore.jks file and placed that on slave server bin folder.

After that i started the slave server to listen by using

./jmeter-server -Djava.rmi.server.hostname=10.xx.xx.xxx

It then starts the slave server.

After that i run the script from master in non-gui mode.

./jmeter -n -t pathtoscript.jmx -l logfilepath.csv -r
Creating summariser
Created the tree successfully using pathtoscript.jmx
Configuring remote engine: 10.xx.xx.xxx
Connection refused to host: 10.xx.xx.xxx; nested exception is:
    java.net.ConnectException: Connection refused (Connection refused)
Failed to configure 10.xx.xx.xxx (this is slave ip)
Configuring remote engine: 10.xx.xx.xxx (this is my master ip)
Connection refused to host: 10.xx.xx.xxx; nested exception is:
    java.net.ConnectException: Connection refused (Connection refused)
Failed to configure 10.xx.xx.xxx (this is my master ip)
Stopping remote engines
Remote engines have been stopped
Error in NonGUIDriver java.lang.RuntimeException: Following remote engines could not be configured:[10.xx.xx.xxx, 10.xx.xx.xxx]


问:
How to map co-ordinates from the image to a 2D surface
I'm trying to map the badminton court coverage by a player. For detecting the player I used a faster RCNN deep learning model. It detects both the players.
I've also extracted their position from the bounding boxes using xmin and xmax coordinates.

 Now I'm planning to map the coordinates to a 2D map of a badminton court.

Value of bounding box coordinates of PB class are
[ymin, xmin, ymax, xmax]
[0.4867423, 0.38700044, 0.7571616, 0.45828968]

I've no clue where to start with.

答:
Will take a more substantial look at this when work clears up, and edit accordingly, but for now my instinct is that you should try a combination of Hough Transform and Ransac to find the corners of the badminton court, perform a perspective transform to get a top view of the court, and use the transformation on the center of the bottom edge of your bounding box as the player coordinate in the transformed court view.

For an approach to finding and transforming the badminton court, this response might prove handy.

Edit 1:

It strikes me that, if the camera is fixed (which I imagine it may very well be), the need for Hough+RANSAC is extraneous. You can simply identify the coordinates of the four corners of the court by hand, and then use OpenCV to transform the image perspective and resize the image to the dimensions of a badminton court. I whipped up a short notebook to demonstrate how to do this.


问:
Image Corner Radius
Is there any way to round the corners of an ImageView through xml layout? And even if not, what are the ways we can achieve that?

PS: The image urls are being fetched from an API. Not from drawable folder

答:
by using Glide library

use

```<code>Glide
  .with(context)
  .load(url)
  .apply(
      RequestOptions()
        .circleCrop())
  .into(imageView)
</code>```

Title: Image Corner Radius

Body:
by using Glide library

use

Glide
  .with(context)
  .load(url)
  .apply(
      RequestOptions()
        .circleCrop())
  .into(imageView)


答:
the simplest would be something like this:

```<code>(with-open [rdr (clojure.java.io/reader "data.txt")]
  (mapv vec (line-seq rdr)))
</code>```

or in case you need strings instead of chars:

```<code>(with-open [rdr (clojure.java.io/reader "data.txt")]
  (mapv #(clojure.string/split % #"") (line-seq rdr)))
</code>```

both return vector of vectors of elements

Title: Is is possible to read from an input file and convert each line of the text file into a vector of strings?

Body:
I have a text file as shown below:

---#--###----
-#---#----##-
####-#-#-#-##
---#---#-#---
-#-####---##-
-#------#----
-############
------------@

Can I read from the input file and get an output in this format

[ ["-" "-" "-" "#" "-" "-" "#" "#" "#" "-" "-" "-" "-"]
  ["-" "#" "-" "-" "-" "#" "-" "-" "-" "-" "#" "#" "-"]
  ["#" "#" "#" "#" "-" "#" "-" "#" "-" "#" "-" "#" "#"]
  ["-" "-" "-" "#" "-" "-" "-" "#" "-" "#" "-" "-" "-"]
  ["-" "#" "-" "#" "#" "#" "#" "-" "-" "-" "#" "#" "-"]
  ["-" "#" "-" "-" "-" "-" "-" "-" "#" "-" "-" "-" "-"]
  ["-" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#"]
  ["-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "@"]
]

I tried reading the input file line by line and adding to a vector:

    (defn loadFile2 []
        (with-open [rdr (clojure.java.io/reader "map.txt")]
        (reduce conj [] (line-seq rdr)))
    )

    (defn convert_input_to_string []
        "Converts"
        ;(def temp )
        (loop [i 0 temp (loadFile2)]
            (if (< i (count temp))

            (recur (inc i) (assoc temp i (str (join (seq (get temp
             i))))) )
            temp
            ))
    )

(convert_input_to_string).

This approach gives me a vector of strings:

[---#--###----
 -#---#----##-
 ####-#-#-#-##
 ---#---#-#---
 -#-####---##-
 -#------#----
 -############
 ------------@
]

I want the vector in this format:

[ ["-" "-" "-" "#" "-" "-" "#" "#" "#" "-" "-" "-" "-"]
  ["-" "#" "-" "-" "-" "#" "-" "-" "-" "-" "#" "#" "-"]
  ["#" "#" "#" "#" "-" "#" "-" "#" "-" "#" "-" "#" "#"]
  ["-" "-" "-" "#" "-" "-" "-" "#" "-" "#" "-" "-" "-"]
  ["-" "#" "-" "#" "#" "#" "#" "-" "-" "-" "#" "#" "-"]
  ["-" "#" "-" "-" "-" "-" "-" "-" "#" "-" "-" "-" "-"]
  ["-" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#"]
  ["-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "@"]]

Body:
the simplest would be something like this:

(with-open [rdr (clojure.java.io/reader "data.txt")]
  (mapv vec (line-seq rdr)))

or in case you need strings instead of chars:

(with-open [rdr (clojure.java.io/reader "data.txt")]
  (mapv #(clojure.string/split % #"") (line-seq rdr)))

both return vector of vectors of elements


问:
how can I convert a char to variable?
In detail:
I need this formula to work.
string = str(z)+":1.0 "+str(z+1)+":0.0"      where z is a variable with a value.

will I be able to input this formula into a dictionary value with a specific key. Like

```<code>dicto={'A': 'str(z)+":1.0 "+str(z+1)+":0.0"'}
</code>```

so that when i see a key value 'A' I should be able to use that formula in the dictionary

答:
As I read your question, you wanted something like this:</p>

```<code>dicto = {'A': lambda x: "{0!s}:1.0 {1!s}:0.0".format(x, x + 1)}
dicto['A'](2)   # '2:1.0 3:0.0'
</code>```

Title: how can I convert a char to variable?

Body:
In detail:
I need this formula to work.
string = str(z)+":1.0 "+str(z+1)+":0.0"      where z is a variable with a value.

will I be able to input this formula into a dictionary value with a specific key. Like

dicto={'A': 'str(z)+":1.0 "+str(z+1)+":0.0"'}

so that when i see a key value 'A' I should be able to use that formula in the dictionary

Body:
As I read your question, you wanted something like this:

dicto = {'A': lambda x: "{0!s}:1.0 {1!s}:0.0".format(x, x + 1)}
dicto['A'](2)   # '2:1.0 3:0.0'


问:
How to calculate two averages of the same class, and get two outputs?
i am stuck in a little situation. I am making a plugin for my school grades to calculate the average.(The avarage might look rong but that's how our'e greades work.)The school site that show the grades is using the same class names. Until now i know how to calculate the average of 1 part.

But is there a way to call  2 classes in a querySelectorAll. like this: [0], [1]?

```<code><script
            var matches = document.querySelectorAll(".course_eval_cell");
            console.log(matches);

            let up = 0;
            let down = 0;

            matches.forEach(function(fraction) {
                var divided = fraction.innerHTML.split("/");
                console.log(divided);
                up += parseInt(divided[0]);
                down += parseInt(divided[1]);
                console.log(up);
                console.log(down);
            });

            var result =   (up / down ) * 100
            console.log(result);
            var result_fixed = result.toFixed(1) + "%";
            console.log(result_fixed);
            document.write('<p id="jstext">' + result_fixed + '</p>');

</script>

<div class="course_eval_row cf" style="width:770px;">
    <div class="course_eval_cell hasGrade" smsctip="true">10/10</div>
    <div class="course_eval_cell hasGrade  ">88/100</div>
</div>

<div class="course_eval_row cf" style="width:770px;">
    <div class="course_eval_cell hasGrade" smsctip="true">4/10</div>
    <div class="course_eval_cell hasGrade  ">34/50</div>
</div>

</code>```

I expect 2 different results, the average of the first grades and the average of the second grades. Thanks for your time.

答:
you can do this</p>

```<code><script>
    var matches = document.querySelectorAll(".course_eval_row");
    console.log(matches);

    matches.forEach(function(fraction) {
      var subNodes = fraction.querySelectorAll(".course_eval_cell");
      let up = 0;
      let down = 0;
      subNodes.forEach(function(sub) {
          var divided = sub.innerHTML.split("/");
          console.log(divided);
          up += parseInt(divided[0]);
          down += parseInt(divided[1]);
          console.log(up);
          console.log(down);
        });
      var result =   (up / down ) * 100
      console.log(result);
      var result_fixed = result.toFixed(1) + "%";
      console.log(result_fixed);
      document.write('<p id="jstext">' + result_fixed + '</p>');
    });
</script>
</code>```

Body:
i am stuck in a little situation. I am making a plugin for my school grades to calculate the average.(The avarage might look rong but that's how our'e greades work.)The school site that show the grades is using the same class names. Until now i know how to calculate the average of 1 part.

But is there a way to call  2 classes in a querySelectorAll. like this: [0], [1]?

10/10

88/100

4/10

34/50

I expect 2 different results, the average of the first grades and the average of the second grades. Thanks for your time.

Body:
you can do this

<script>
    var matches = document.querySelectorAll(".course_eval_row");
    console.log(matches);

    matches.forEach(function(fraction) {
      var subNodes = fraction.querySelectorAll(".course_eval_cell");
      let up = 0;
      let down = 0;
      subNodes.forEach(function(sub) {
          var divided = sub.innerHTML.split("/");
          console.log(divided);
          up += parseInt(divided[0]);
          down += parseInt(divided[1]);
          console.log(up);
          console.log(down);
        });
      var result =   (up / down ) * 100
      console.log(result);
      var result_fixed = result.toFixed(1) + "%";
      console.log(result_fixed);
      document.write('<p id="jstext">' + result_fixed + '</p>');
    });
</script>


问:
C NULL type in CGO
I have a C function that returns NULL when an exception occurs. How can I check whether the returned value is NULL or not in Go since it has no built-in types to represent C NULL. Below is my code

retVal := C.myfunc()

if retVal == nil {
  // handle the error
}

```

答:
I think you can use nil to test if the c function returns NULL. Try the following code:

```<code>package main

/*
#include <stdio.h>
#include <stdlib.h>

int* cfunc(int i) {
    if (i == 0) {
        return NULL;
    }

    int *p = (int*)malloc(sizeof(int));
    *p = 100;
    return p;
}
*/
import "C"

import "fmt"
import "unsafe"

func call_cfunc(i int32) {
    ret := C.cfunc(C.int(i))
    if ret == nil {
        fmt.Println("nil")
    } else {
        fmt.Println(*ret)
        C.free(unsafe.Pointer(ret))
    }
}

func main() {
    call_cfunc(0)
    call_cfunc(1)
}
</code>```

Title: C NULL type in CGO

Body:
I think you can use nil to test if the c function returns NULL. Try the following code:

package main

/*
#include <stdio.h>
#include <stdlib.h>

int* cfunc(int i) {
    if (i == 0) {
        return NULL;
    }

    int *p = (int*)malloc(sizeof(int));
    *p = 100;
    return p;
}
*/
import "C"

import "fmt"
import "unsafe"

func call_cfunc(i int32) {
    ret := C.cfunc(C.int(i))
    if ret == nil {
        fmt.Println("nil")
    } else {
        fmt.Println(*ret)
        C.free(unsafe.Pointer(ret))
    }
}

func main() {
    call_cfunc(0)
    call_cfunc(1)
}


问:
Why it is giving me 'this.state.UserData.map' is not a function?
I am getting an error in my code 'this.state.UserData.map' is not a function . i want get list from the database using fetch. i think i am forgetting something.
please help me remove this error. thanks in advance.
Here is my complete code to show list...</p>

```<code>import React from 'react';
import ReactDOM from 'react-dom';
export default class FetchedData extends React.Component{
  constructor(props){
    super(props);
    this.state={ UserData:[] };
    this.headers=[
      {key:1,label:'Name'},
      {key:2,label:'Department'},
      {key:3,label:'Marks'},
    ];
  }

  componentDidMount(){
    fetch("https://www.veomit.com/test/zend/api/fetch.php")
    .then(response => {
                return response.json();
            })
    .then(result => {
                this.setState({
                    UserData:result
                })
        .catch(error => {
        console.log(
          "An error occurred while trying to fetch data from Foursquare: " +error
        );
      });
    });
  }
  render(){
    return(
      <div>
      <table className="table table-bordered">
          <thead>
            <tr>
              {
                        this.headers.map(function(h) {
                            return (
                                <th key = {h.key}>{h.label}</th>
                            );
                        })
                        }
            </tr>
          </thead>
          <tbody>
              {
                        this.state.UserData.map(function(item){
                        return (
                                <tr>
                                  <td>{item.name}</td>
                                  <td>{item.department}</td>
                                  <td>{item.marks}</td>
                                </tr>
                            );
                        })
                    }
          </tbody>
      </table>
      </div>
    );
  }
}
````````
</code>```

答:
Please replace your code I hope it's working for you.

Thanks

```<code> import React from 'react';
    import ReactDOM from 'react-dom';
    export default class FetchedData extends React.Component{
      constructor(props){
        super(props);
        this.state={ UserData:[] };
        this.headers=[
          {key:1,label:'Name'},
          {key:2,label:'Department'},
          {key:3,label:'Marks'},
        ];
      }

       componentWillMount() {
            fetch("https://www.veomit.com/test/zend/api/fetch.php")
            .then(response => {
                 return response.json();
            })
            .then(result => {
                this.setState({
                    UserData: result
                });
             })
             .catch(function(error) {
                    console.log(
                    "An error occurred while trying to fetch data from Foursquare: " +
                          error
                    );
            });
        }
      render(){
        return(
          <div>
          <table className="table table-bordered">
              <thead>
                <tr>
                  {
                            this.headers.map(function(h) {
                                return (
                                    <th key = {h.key}>{h.label}</th>
                                );
                            })
                            }
                </tr>
              </thead>
              <tbody>
                  { this.state.UserData.length > 0 ?
                         this.state.UserData.map((item,index) => (
                             <tr key={index}>
                                      <td>{item.name}</td>
                                      <td>{item.department}</td>
                                      <td>{item.marks}</td>
                                    </tr>
                          ))
                          ) : (
                               <tr>
                                  <td colspan="3">No record found.</td>
                                </tr>
                              )}
                  </tbody>
          </table>
          </div>
        );
      }
    }
    ````````
</code>```

Body:
I am getting an error in my code 'this.state.UserData.map' is not a function . i want get list from the database using fetch. i think i am forgetting something.
please help me remove this error. thanks in advance.
Here is my complete code to show list...

import React from 'react';
import ReactDOM from 'react-dom';
export default class FetchedData extends React.Component{
  constructor(props){
    super(props);
    this.state={ UserData:[] };
    this.headers=[
      {key:1,label:'Name'},
      {key:2,label:'Department'},
      {key:3,label:'Marks'},
    ];
  }

  componentDidMount(){
    fetch("https://www.veomit.com/test/zend/api/fetch.php")
    .then(response => {
                return response.json();
            })
    .then(result => {
                this.setState({
                    UserData:result
                })
        .catch(error => {
        console.log(
          "An error occurred while trying to fetch data from Foursquare: " +error
        );
      });
    });
  }
  render(){
    return(

              {
                        this.headers.map(function(h) {
                            return (
                                {h.label}
                            );
                        })
                        }

              {
                        this.state.UserData.map(function(item){
                        return (

                                  {item.name}
                                  {item.department}
                                  {item.marks}

                            );
                        })
                    }

    );
  }
}
````````

Body:
Please replace your code I hope it's working for you.

Thanks

 import React from 'react';
    import ReactDOM from 'react-dom';
    export default class FetchedData extends React.Component{
      constructor(props){
        super(props);
        this.state={ UserData:[] };
        this.headers=[
          {key:1,label:'Name'},
          {key:2,label:'Department'},
          {key:3,label:'Marks'},
        ];
      }

       componentWillMount() {
            fetch("https://www.veomit.com/test/zend/api/fetch.php")
            .then(response => {
                 return response.json();
            })
            .then(result => {
                this.setState({
                    UserData: result
                });
             })
             .catch(function(error) {
                    console.log(
                    "An error occurred while trying to fetch data from Foursquare: " +
                          error
                    );
            });
        }
      render(){
        return(
          <div>
          <table className="table table-bordered">
              <thead>
                <tr>
                  {
                            this.headers.map(function(h) {
                                return (
                                    <th key = {h.key}>{h.label}</th>
                                );
                            })
                            }
                </tr>
              </thead>
              <tbody>
                  { this.state.UserData.length > 0 ?
                         this.state.UserData.map((item,index) => (
                             <tr key={index}>
                                      <td>{item.name}</td>
                                      <td>{item.department}</td>
                                      <td>{item.marks}</td>
                                    </tr>
                          ))
                          ) : (
                               <tr>
                                  <td colspan="3">No record found.</td>
                                </tr>
                              )}
                  </tbody>
          </table>
          </div>
        );
      }
    }
    ````````


问:
android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()
The app is crashing when I'm trying to open a file. It works below Android Nougat, but on Android Nougat it crashes. It only crashes when I try to open a file from the SD card, not from the system partition. Some permission problem?

Sample code:

```<code>File file = new File("/storage/emulated/0/test.txt");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "text/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent); // Crashes on this line
</code>```

Log:

android.os.FileUriExposedException:
  file:///storage/emulated/0/test.txt exposed beyond app through
  Intent.getData()

Edit:

When targeting Android Nougat, file:// URIs are not allowed anymore. We should use content:// URIs instead. However, my app needs to open files in root directories. Any ideas?

答:
I know this is a pretty old question but this answer is for future viewers. So I've encountered a similar problem and after researching, I've found an alternative to this approach.

Your Intent here
for eg: To view your image from your path in Kotlin

```<code> val intent = Intent()
 intent.setAction(Intent.ACTION_VIEW)
 val file = File(currentUri)
 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
 val contentURI = getContentUri(context!!, file.absolutePath)
 intent.setDataAndType(contentURI,"image/*")
 startActivity(intent)
</code>```

Main Function below

```<code>private fun getContentUri(context:Context, absPath:String):Uri? {
        val cursor = context.getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            arrayOf<String>(MediaStore.Images.Media._ID),
            MediaStore.Images.Media.DATA + "=? ",
            arrayOf<String>(absPath), null)
        if (cursor != null && cursor.moveToFirst())
        {
            val id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID))
            return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Integer.toString(id))
        }
        else if (!absPath.isEmpty())
        {
            val values = ContentValues()
            values.put(MediaStore.Images.Media.DATA, absPath)
            return context.getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        }
        else
        {
            return null
        }
    }
</code>```

Likewise, instead of an image, you can use any other file format like pdf and in my case, it worked just fine

Body:
The app is crashing when I'm trying to open a file. It works below Android Nougat, but on Android Nougat it crashes. It only crashes when I try to open a file from the SD card, not from the system partition. Some permission problem?

Sample code:

File file = new File("/storage/emulated/0/test.txt");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "text/*");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent); // Crashes on this line

Log:

android.os.FileUriExposedException:
  file:///storage/emulated/0/test.txt exposed beyond app through
  Intent.getData()

Edit:

When targeting Android Nougat, file:// URIs are not allowed anymore. We should use content:// URIs instead. However, my app needs to open files in root directories. Any ideas?

Body:
I know this is a pretty old question but this answer is for future viewers. So I've encountered a similar problem and after researching, I've found an alternative to this approach.

Your Intent here
for eg: To view your image from your path in Kotlin

 val intent = Intent()
 intent.setAction(Intent.ACTION_VIEW)
 val file = File(currentUri)
 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
 val contentURI = getContentUri(context!!, file.absolutePath)
 intent.setDataAndType(contentURI,"image/*")
 startActivity(intent)

Main Function below

private fun getContentUri(context:Context, absPath:String):Uri? {
        val cursor = context.getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            arrayOf<String>(MediaStore.Images.Media._ID),
            MediaStore.Images.Media.DATA + "=? ",
            arrayOf<String>(absPath), null)
        if (cursor != null && cursor.moveToFirst())
        {
            val id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID))
            return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Integer.toString(id))
        }
        else if (!absPath.isEmpty())
        {
            val values = ContentValues()
            values.put(MediaStore.Images.Media.DATA, absPath)
            return context.getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        }
        else
        {
            return null
        }
    }

Likewise, instead of an image, you can use any other file format like pdf and in my case, it worked just fine


问:
this.get(...).then is not a function when using init: ember.js
I am using init() in my component to load some data for a dropdown. On refresh it works but when I leave the tab to another tab then come back I get the following error:
index.js:143322 Uncaught TypeError: this.get(...).then is not a function

This code is in my init function and I suspect it has something to do with how ember.js renders but I am struggling to figure out how to make it work. I tried using the other lifestyle hooks but none of them worked.

This is the init function which is in a component:

```<code>init() {
      this._super(...arguments)
      this.get('popularTags').then(function(result) {
        const newArray = []
        for (var i = 0; i < result.length; i++) {
          newArray.push({
            name: result[i],
            value: result[i],
            group: 'Popular'
          })
        }
        const popularTags = this.get('popularTags')
        this.set('popularTags', newArray)
        this.get('queryResults').then(function(result) {
          const tagArray = []
          for (var i = 0; i < result.length; i++) {
            let popular = newArray.filter(tag => tag['value'] === result[i].value)

            if (popular.length === 0) {
              tagArray.push({
                name: result[i].value,
                value: result[i].value,
                group: ''
              })
            }
          }
          const queryResults = this.get('queryResults')

          return this.set('queryResults', tagArray)
        }.bind(this))

      }.bind(this))

    },
</code>```

答:
There is something about your above example that I just don't understand. You seem to be getting and setting both the popularTags and queryResults properties. I'm not sure if that's just an issue in your example or something else - I'm going to assume it's an example issue and break this down a bit more generally:

Doing this much work in init isn't generally a good idea, so much so that it is slated for removal from the upcoming glimmer component API. In particular set inside any of the lifecycle hooks is a recipe for weird errors when the component gets removed from the DOM. While you can use a tool like ember-concurrency to help break this up and deal with set my suggestion would be to split this up into several computed properties. This might look something like:

```<code>import Component from '@ember/component';
import { computed } from '@ember/object';

export default Component.extend({
  popularTags: computed('tags.[]', function(){
    return this.tags.filter(tag => tag.isPopular);
  }),
  queryResults: computed('popularTags.[]', function(){
    return this.popularTags.map(tag => {
      return {
        name: tag.name,
        value: tag.description
      };
    });
  }),
});
</code>```

Computed Properties like these are the way to express data transformations in Ember. They rely on some initial data that is passed into the component and then modify it for use. In my above example I've assumed that tags gets passed in, but you can see that queryResults relies on the results of popularTags, in this way several different data transformations can be executed in order.

While loading asyncronous data in components can work just fine when you are first building and Ember.js application I would suggest that you confine all of your data loading to the Route's Model Hook as it is better suited to async work and will then give you data you can pass directly into the component without needing to worry about the difficulties in loading it there.

Body:
I am using init() in my component to load some data for a dropdown. On refresh it works but when I leave the tab to another tab then come back I get the following error:
index.js:143322 Uncaught TypeError: this.get(...).then is not a function

This code is in my init function and I suspect it has something to do with how ember.js renders but I am struggling to figure out how to make it work. I tried using the other lifestyle hooks but none of them worked.

This is the init function which is in a component:

init() {
      this._super(...arguments)
      this.get('popularTags').then(function(result) {
        const newArray = []
        for (var i = 0; i < result.length; i++) {
          newArray.push({
            name: result[i],
            value: result[i],
            group: 'Popular'
          })
        }
        const popularTags = this.get('popularTags')
        this.set('popularTags', newArray)
        this.get('queryResults').then(function(result) {
          const tagArray = []
          for (var i = 0; i < result.length; i++) {
            let popular = newArray.filter(tag => tag['value'] === result[i].value)

            if (popular.length === 0) {
              tagArray.push({
                name: result[i].value,
                value: result[i].value,
                group: ''
              })
            }
          }
          const queryResults = this.get('queryResults')

          return this.set('queryResults', tagArray)
        }.bind(this))

      }.bind(this))

    },

Body:
There is something about your above example that I just don't understand. You seem to be getting and setting both the popularTags and queryResults properties. I'm not sure if that's just an issue in your example or something else - I'm going to assume it's an example issue and break this down a bit more generally:

Doing this much work in init isn't generally a good idea, so much so that it is slated for removal from the upcoming glimmer component API. In particular set inside any of the lifecycle hooks is a recipe for weird errors when the component gets removed from the DOM. While you can use a tool like ember-concurrency to help break this up and deal with set my suggestion would be to split this up into several computed properties. This might look something like:

import Component from '@ember/component';
import { computed } from '@ember/object';

export default Component.extend({
  popularTags: computed('tags.[]', function(){
    return this.tags.filter(tag => tag.isPopular);
  }),
  queryResults: computed('popularTags.[]', function(){
    return this.popularTags.map(tag => {
      return {
        name: tag.name,
        value: tag.description
      };
    });
  }),
});

Computed Properties like these are the way to express data transformations in Ember. They rely on some initial data that is passed into the component and then modify it for use. In my above example I've assumed that tags gets passed in, but you can see that queryResults relies on the results of popularTags, in this way several different data transformations can be executed in order.

While loading asyncronous data in components can work just fine when you are first building and Ember.js application I would suggest that you confine all of your data loading to the Route's Model Hook as it is better suited to async work and will then give you data you can pass directly into the component without needing to worry about the difficulties in loading it there.


问:
How can I change the size of the payment icons in the Shopify 'Brooklyn' theme?
I am using Shopify with the 'Brooklyn' theme and i need to make the payment icons in the footer bigger. I've tried to change the CSS code of the img class to change the size of the icons, but i just could make them smaller and not bigger.
Any idea how to change it?</p>

```<code>.payment-icons {
  @include prefix('user-select', 'none');
  cursor: default;
  margin-bottom: 0;

  li {
    margin: 0 ($gutter / 4) ($gutter / 4);
    cursor: default;
  }

  .icon {
    font-size: 30px;
    line-height: 30px;
  }

  .fallback-text {
    text-transform: capitalize;
  }
}
</code>```

答:
Add the below style in your custom stylesheet -

```<code>.payment-icons .icon {
    width: <width in px> !important;
    height: <height in px> !important;
}
</code>```

Update:
For your store add the below style

```<code>.payment-icons > img{
    min-width: <width in px> !important;
    min-height: <height in px> !important;
}
</code>```

Body:
I am using Shopify with the 'Brooklyn' theme and i need to make the payment icons in the footer bigger. I've tried to change the CSS code of the img class to change the size of the icons, but i just could make them smaller and not bigger.
Any idea how to change it?

.payment-icons {
  @include prefix('user-select', 'none');
  cursor: default;
  margin-bottom: 0;

  li {
    margin: 0 ($gutter / 4) ($gutter / 4);
    cursor: default;
  }

  .icon {
    font-size: 30px;
    line-height: 30px;
  }

  .fallback-text {
    text-transform: capitalize;
  }
}

Body:
Add the below style in your custom stylesheet -

.payment-icons .icon {
    width: <width in px> !important;
    height: <height in px> !important;
}

Update:
For your store add the below style

.payment-icons > img{
    min-width: <width in px> !important;
    min-height: <height in px> !important;
}


答:
The data is an object - you need to convert it to an array with Object.values:

```<code>UserData: Object.values(result)
</code>```

Title: Why it is giving me 'this.state.UserData.map' is not a function?

Body:
The data is an object - you need to convert it to an array with Object.values:

UserData: Object.values(result)


问:
Sharing Variables Between Multiple Instances of Excel
I have multiple instances of Excel calculating different parts of a problem and I want to be able to track total progress as the number of iterations completed across each instance. How can I share variables between instances of Excel?

My current thought is storing these numbers in the name manager of a master workbook and having the master workbook sum up the value for each name as a total number of iterations completed number. I've also tried the same concept by referencing the hidden namespace in the master instance of Excel as described by Chip Pearson here: http://www.cpearson.com/excel/hidden.htm. Ultimately I'm struggling to keep the progress numbers across instances in memory. I do not want to write to a file that the master Excel instance references as that would slow things down quite a bit.

Inside of a working instance of Excel would be something like the following code to transmit back it's current progress to the namespace of the master workbook:

```<code>Dim xlApp As Excel.Application
Set xlApp = GetObject(MasterPath).Application
'The MasterPath is defined as the full path of the master instance: ActiveWorkbook.FullName
With xlApp
    .Workbooks(MasterName).Activate
    .ActiveWorkbook.Names("Thread_" & i & "_iter").RefersTo = "=" & CStr(i - seqFrom + 1)
End With
</code>```

The above code is what is giving me errors. It gets stuck in an infinite loop. When I remove it, everything executes as expected.

In the master workbook would be something like the following to show the total progress across all instances:

```<code>For thread = 1 To cThreads
    progress_Arr(thread) = CLng(Right(ThisWorkbook.Names("Thread_" & thread & "_iter").RefersTo, Len(ThisWorkbook.Names("Thread_" & thread & "_iter").RefersTo) - 1))
    progress = progress + progress_Arr(thread)
    Debug.Print "Thread " & thread & ": " & progress_Arr(thread)
Next thread
</code>```

I would ultimately like to be able to compile all of the iterations in the master instance of Excel.

答:
Ok expanding on my comment here's my rough and ready test code: spin up a few "slave" Excel instances, load in a copy of the "driver" workbook (as readonly), and then give each slave workbook a reference to the master workbook, which they can use to call a public LogProgress method on the ThisWorkbook object.

In a regular module:

```<code>Option Explicit

Dim col As Collection '<< In the master, stores references to slave application instances
                      '    Not really used here though

'For "slave" workbooks - dummy "do some work" long-running
'   routine which periodically reports back
Public Sub DoWork()
    Dim n As Long
    'kick something off...
    For n = 1 To 20
        Application.Wait Now + TimeSerial(0, 0, 1)
        ThisWorkbook.ReportWork n '<< update master
    Next n
End Sub

'Creates slave instances loaded with copies of this workbook
'  and a reference to the master workbook, and loads them into "col"
Sub InitSlaves()
    Dim x As Long, app
    ThisWorkbook.Save
    Debug.Print "Master instance", Application.Hwnd
    Set col = New Collection
    For x = 1 To 5
        col.Add XlInstance(ThisWorkbook.FullName)
    Next x
End Sub

'Set up and return a new Excel instance
Function XlInstance(wb As String)
    Dim app, wkb
    Set app = CreateObject("excel.application")
    app.Visible = True
    Debug.Print "Slave instance", app.Hwnd
    Set wkb = app.Workbooks.Open(wb, ReadOnly:=True)
    Set wkb.Master = ThisWorkbook
    wkb.StartWork
    Set XlInstance = app
End Function
</code>```

In the ThisWorkbook module:

```<code>Option Explicit

Dim masterWb As Object '<< in a slave workbook, a reference to the master wb

'In a slave workbook, gets a reference to the master workbook
'  Note: you *must* use 'As Object' here or you can't call the custom
'        methods later (because a "WorkBook"-type doesn't have them)
Public Property Set Master(wb As Object)
    Set masterWb = wb
End Property

'Gets called on the slave workbooks from the master
Public Sub StartWork()
   Application.OnTime Now, "DoWork"
End Sub

'From a slave, send a message back to the master workbook
Public Sub ReportWork(msg)
    masterWb.LogProgress Application.Hwnd, msg
End Sub

'In the master, get a message from a slave workbook
Public Sub LogProgress(id, msg)
    Dim m
    m = Application.Match(id, Sheet1.Columns(1), 0)
    If IsError(m) Then
        m = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row + 1
        Sheet1.Cells(m, 1).Value = id
    End If
    Sheet1.Cells(m, 2).Value = msg
End Sub
</code>```

Body:
I have multiple instances of Excel calculating different parts of a problem and I want to be able to track total progress as the number of iterations completed across each instance. How can I share variables between instances of Excel?

My current thought is storing these numbers in the name manager of a master workbook and having the master workbook sum up the value for each name as a total number of iterations completed number. I've also tried the same concept by referencing the hidden namespace in the master instance of Excel as described by Chip Pearson here: http://www.cpearson.com/excel/hidden.htm. Ultimately I'm struggling to keep the progress numbers across instances in memory. I do not want to write to a file that the master Excel instance references as that would slow things down quite a bit.

Inside of a working instance of Excel would be something like the following code to transmit back it's current progress to the namespace of the master workbook:

Dim xlApp As Excel.Application
Set xlApp = GetObject(MasterPath).Application
'The MasterPath is defined as the full path of the master instance: ActiveWorkbook.FullName
With xlApp
    .Workbooks(MasterName).Activate
    .ActiveWorkbook.Names("Thread_" & i & "_iter").RefersTo = "=" & CStr(i - seqFrom + 1)
End With

The above code is what is giving me errors. It gets stuck in an infinite loop. When I remove it, everything executes as expected.

In the master workbook would be something like the following to show the total progress across all instances:

For thread = 1 To cThreads
    progress_Arr(thread) = CLng(Right(ThisWorkbook.Names("Thread_" & thread & "_iter").RefersTo, Len(ThisWorkbook.Names("Thread_" & thread & "_iter").RefersTo) - 1))
    progress = progress + progress_Arr(thread)
    Debug.Print "Thread " & thread & ": " & progress_Arr(thread)
Next thread

I would ultimately like to be able to compile all of the iterations in the master instance of Excel.

Body:
Ok expanding on my comment here's my rough and ready test code: spin up a few "slave" Excel instances, load in a copy of the "driver" workbook (as readonly), and then give each slave workbook a reference to the master workbook, which they can use to call a public LogProgress method on the ThisWorkbook object.

In a regular module:

Option Explicit

Dim col As Collection '<< In the master, stores references to slave application instances
                      '    Not really used here though

'For "slave" workbooks - dummy "do some work" long-running
'   routine which periodically reports back
Public Sub DoWork()
    Dim n As Long
    'kick something off...
    For n = 1 To 20
        Application.Wait Now + TimeSerial(0, 0, 1)
        ThisWorkbook.ReportWork n '<< update master
    Next n
End Sub

'Creates slave instances loaded with copies of this workbook
'  and a reference to the master workbook, and loads them into "col"
Sub InitSlaves()
    Dim x As Long, app
    ThisWorkbook.Save
    Debug.Print "Master instance", Application.Hwnd
    Set col = New Collection
    For x = 1 To 5
        col.Add XlInstance(ThisWorkbook.FullName)
    Next x
End Sub

'Set up and return a new Excel instance
Function XlInstance(wb As String)
    Dim app, wkb
    Set app = CreateObject("excel.application")
    app.Visible = True
    Debug.Print "Slave instance", app.Hwnd
    Set wkb = app.Workbooks.Open(wb, ReadOnly:=True)
    Set wkb.Master = ThisWorkbook
    wkb.StartWork
    Set XlInstance = app
End Function

In the ThisWorkbook module:

Option Explicit

Dim masterWb As Object '<< in a slave workbook, a reference to the master wb

'In a slave workbook, gets a reference to the master workbook
'  Note: you *must* use 'As Object' here or you can't call the custom
'        methods later (because a "WorkBook"-type doesn't have them)
Public Property Set Master(wb As Object)
    Set masterWb = wb
End Property

'Gets called on the slave workbooks from the master
Public Sub StartWork()
   Application.OnTime Now, "DoWork"
End Sub

'From a slave, send a message back to the master workbook
Public Sub ReportWork(msg)
    masterWb.LogProgress Application.Hwnd, msg
End Sub

'In the master, get a message from a slave workbook
Public Sub LogProgress(id, msg)
    Dim m
    m = Application.Match(id, Sheet1.Columns(1), 0)
    If IsError(m) Then
        m = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row + 1
        Sheet1.Cells(m, 1).Value = id
    End If
    Sheet1.Cells(m, 2).Value = msg
End Sub


问:
ArrayList is being initialised everytime the CustomDialogFragment is opened
I use Arraylist in CustomDialogFragment to store values each time when the user checks a checkbox. And removes the values when the user unchecks it. The issue is that each time the user dismisses the dialog, the values in the arraylist gets deleted. I think it's because of reinitialisation of the array  each time when the user  opens the dialog.

I was thinking to store the array in shared preferences, but not sure whether that is the right way to do it. Kindly suggest me how to do it effectively.

CarTypeDialogFragment.java

```<code>public class CarTypeDialogFragment extends DialogFragment {

public interface OnInputListener {
    void sendInput(String input);
}

public OnInputListener mOnInputListener;

CheckBox type1, type2, type4;
String SedanCheckBoxesVal, SUVCheckBoxesVal, HatchBackCheckBoxesVal;

ArrayList<String> myList = new ArrayList<String>();
View v;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
    if (getArguments() != null) {
        //totalCars = getArguments().getString("cars","");
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    if (v != null) {
        if ((ViewGroup) v.getParent() != null)
            ((ViewGroup) v.getParent()).removeView(v);
        return v;
    }
    v = inflater.inflate(R.layout.fragment_restype_dialog, container, false);

    type1 = (CheckBox) v.findViewById(R.id.checkBox);
    type1.setChecked(getFromSP("cb1"));

    type2 = (CheckBox) v.findViewById(R.id.checkBox2);
    type2.setChecked(getFromSP("cb2"));

    type4 = (CheckBox) v.findViewById(R.id.checkBox4);
    type4.setChecked(getFromSP("cb4"));

    type1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (((CheckBox) view).isChecked()) {
                SedanCheckBoxesVal = "'Accord','Avlon','Challenger'";
                saveInSp("cb1", true);
                myList.add(SedanCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                saveInSp("cb1enable", false);

            } else {
                myList.remove(SedanCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                saveInSp("cb1", false);
            }
         }
    });

    type2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //is chkIos checked?

            if (((CheckBox) view).isChecked()) {
                SUVCheckBoxesVal = "'GMC','BMW'";
                saveInSp("cb2", true);
                myList.add(SUVCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                saveInSp("cb2enable", false);

            } else {
                myList.remove(SUVCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                saveInSp("cb2", false);
            }
        }
    });

    type4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //is chkIos checked?

            if (((CheckBox) view).isChecked()) {
                HatchBackCheckBoxesVal = "'Polo','Micra','MiniCooper'";
                saveInSp("cb4", true);
                myList.add(HatchBackCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                saveInSp("cb4enable", false);
                type4.setEnabled(false);

            } else {
                myList.remove(HatchBackCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                mOnInputListener.sendInput("");
                saveInSp("cb4", false);
            }
        }
    });
    return v;
}

private boolean getFromSP(String key) {
    SharedPreferences preferences = getContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
    return preferences.getBoolean(key, false);
}

private void saveInSp(String key, boolean value) {
    SharedPreferences preferences = getContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putBoolean(key, value);
    editor.commit();

}

@Override
public void onStart() {
    super.onStart();

    Window window = getDialog().getWindow();
    WindowManager.LayoutParams windowParams = window.getAttributes();
    windowParams.dimAmount = 0.00f;
    windowParams.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
    window.setAttributes(windowParams);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        mOnInputListener = (OnInputListener) getActivity();
    } catch (ClassCastException e) {
        Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage());
    }
}

@Override
public void onDestroyView() {
    //workaround for this issue: https://code.google.com/p/android/issues/detail?id=17423 (unable to retain instance after configuration change)
    if (getDialog() != null && getRetainInstance())
        getDialog().setDismissMessage(null);
    super.onDestroyView();
}
}
</code>```

答:
This is okay to save your string list to SharedPreferences considering you're not saving a lot of data.

In this case it is okay to save your list in SharedPreferences.

Body:
I use Arraylist in CustomDialogFragment to store values each time when the user checks a checkbox. And removes the values when the user unchecks it. The issue is that each time the user dismisses the dialog, the values in the arraylist gets deleted. I think it's because of reinitialisation of the array  each time when the user  opens the dialog.

I was thinking to store the array in shared preferences, but not sure whether that is the right way to do it. Kindly suggest me how to do it effectively.

CarTypeDialogFragment.java

public class CarTypeDialogFragment extends DialogFragment {

public interface OnInputListener {
    void sendInput(String input);
}

public OnInputListener mOnInputListener;

CheckBox type1, type2, type4;
String SedanCheckBoxesVal, SUVCheckBoxesVal, HatchBackCheckBoxesVal;

ArrayList<String> myList = new ArrayList<String>();
View v;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
    if (getArguments() != null) {
        //totalCars = getArguments().getString("cars","");
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    if (v != null) {
        if ((ViewGroup) v.getParent() != null)
            ((ViewGroup) v.getParent()).removeView(v);
        return v;
    }
    v = inflater.inflate(R.layout.fragment_restype_dialog, container, false);

    type1 = (CheckBox) v.findViewById(R.id.checkBox);
    type1.setChecked(getFromSP("cb1"));

    type2 = (CheckBox) v.findViewById(R.id.checkBox2);
    type2.setChecked(getFromSP("cb2"));

    type4 = (CheckBox) v.findViewById(R.id.checkBox4);
    type4.setChecked(getFromSP("cb4"));

    type1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (((CheckBox) view).isChecked()) {
                SedanCheckBoxesVal = "'Accord','Avlon','Challenger'";
                saveInSp("cb1", true);
                myList.add(SedanCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                saveInSp("cb1enable", false);

            } else {
                myList.remove(SedanCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                saveInSp("cb1", false);
            }
         }
    });

    type2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //is chkIos checked?

            if (((CheckBox) view).isChecked()) {
                SUVCheckBoxesVal = "'GMC','BMW'";
                saveInSp("cb2", true);
                myList.add(SUVCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                saveInSp("cb2enable", false);

            } else {
                myList.remove(SUVCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                saveInSp("cb2", false);
            }
        }
    });

    type4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //is chkIos checked?

            if (((CheckBox) view).isChecked()) {
                HatchBackCheckBoxesVal = "'Polo','Micra','MiniCooper'";
                saveInSp("cb4", true);
                myList.add(HatchBackCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                saveInSp("cb4enable", false);
                type4.setEnabled(false);

            } else {
                myList.remove(HatchBackCheckBoxesVal);
                mOnInputListener.sendInput(TextUtils.join("", myList));
                mOnInputListener.sendInput("");
                saveInSp("cb4", false);
            }
        }
    });
    return v;
}

private boolean getFromSP(String key) {
    SharedPreferences preferences = getContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
    return preferences.getBoolean(key, false);
}

private void saveInSp(String key, boolean value) {
    SharedPreferences preferences = getContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putBoolean(key, value);
    editor.commit();

}

@Override
public void onStart() {
    super.onStart();

    Window window = getDialog().getWindow();
    WindowManager.LayoutParams windowParams = window.getAttributes();
    windowParams.dimAmount = 0.00f;
    windowParams.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
    window.setAttributes(windowParams);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        mOnInputListener = (OnInputListener) getActivity();
    } catch (ClassCastException e) {
        Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage());
    }
}

@Override
public void onDestroyView() {
    //workaround for this issue: https://code.google.com/p/android/issues/detail?id=17423 (unable to retain instance after configuration change)
    if (getDialog() != null && getRetainInstance())
        getDialog().setDismissMessage(null);
    super.onDestroyView();
}
}


问:
Delete customer address in single query
Is there any way to delete customer addresses in a single query.

I know we can fetch customer address object and delete one by one record in the loop but it's a very time-consuming process so I want to delete customer addresses in a single query.

For example, customer id is "1234" and the customer has 15 addresses.

I am very new in Magento and I have not cleared Magento 1 database structure so please help me how can I delete customer addresses in a single query in Magento 1.

答:
Please try with below url, customer adresses delete with addressid.

Deleting customer addresses in magento

Title: Delete customer address in single query


问:
How to search and delete characters in string
I'm trying to convert .fsp files to strings but new .fsp file is very abnormal. It contains some undesirable characters that I want to delete from string. How can I make it?

I have tried to search char in string and delete them but I dont know how to make it.

The string looks like this:

string s;

```<code>s = 144˙037˙412˙864;
</code>```

and I need to make it just like that

```<code>s = 144037412864;
</code>```

So I except result like this:

```<code>string s = 144037412864;
</code>```

Thank you for help.

答:
This problem has two parts, first we need to identify any characters in the string which we don't want. From your use case it seems that anything that is not numeric needs to go. This is simple enough as the standard library defines a function std::isdigit (simply add the following inclusion "#include <locale>") which takes a character and returns a bool which indicates whether or not the character is numeric.

Second we need a way to quickly and cleanly remove all occurrences of these from the string. Thus we can use the 'Erase Remove' idiom to iterate through the string and do what we want.

```<code>string s = "123'4'5";
s.erase(std::remove_if(s.begin(), s.end(), [](char x)->bool {return !std::isdigit(x);}), s.end());
</code>```

In the snippit above we're calling erase on the string which takes two iterators, the first refers to where we want to begin to delete from and the second tells the call where we want to delete to. The magic in this trick is actually all in the call to remove_if (include "#include <algorithm>" for it). remove_if actually works by shifting the elements (or characters) of string forward to the end of the string.

So "123'4'5'" becomes "12345'''", then it returns an iterator to where it shifted these characters to which is then passed to erase to tell it remove the characters starting here. In the end we're left with "12345" as expected.

Edit: Forgot to mention, remove_if also takes a predicate here I'm using a lambda which takes a character and returns a bool.

Body:
I'm trying to convert .fsp files to strings but new .fsp file is very abnormal. It contains some undesirable characters that I want to delete from string. How can I make it?

I have tried to search char in string and delete them but I dont know how to make it.

The string looks like this:

string s;

s = 144˙037˙412˙864;

and I need to make it just like that

s = 144037412864;

So I except result like this:

string s = 144037412864;

Thank you for help.

Body:
This problem has two parts, first we need to identify any characters in the string which we don't want. From your use case it seems that anything that is not numeric needs to go. This is simple enough as the standard library defines a function std::isdigit (simply add the following inclusion "#include <locale>") which takes a character and returns a bool which indicates whether or not the character is numeric.

Second we need a way to quickly and cleanly remove all occurrences of these from the string. Thus we can use the 'Erase Remove' idiom to iterate through the string and do what we want.

string s = "123'4'5";
s.erase(std::remove_if(s.begin(), s.end(), [](char x)->bool {return !std::isdigit(x);}), s.end());

In the snippit above we're calling erase on the string which takes two iterators, the first refers to where we want to begin to delete from and the second tells the call where we want to delete to. The magic in this trick is actually all in the call to remove_if (include "#include <algorithm>" for it). remove_if actually works by shifting the elements (or characters) of string forward to the end of the string.

So "123'4'5'" becomes "12345'''", then it returns an iterator to where it shifted these characters to which is then passed to erase to tell it remove the characters starting here. In the end we're left with "12345" as expected.

Edit: Forgot to mention, remove_if also takes a predicate here I'm using a lambda which takes a character and returns a bool.


问:
Output SQL single transactions that has multiple sales items that belonging to different item group configurations
I need a query that can return a transaction that has multiple items. The transaction must have multiple items that belong to a combination of the buckets below:

100 Items are grouped into three buckets. Bucket 49, bucket 50, and bucket 56.

There is item 1 configured with bucket 49.

There is a item 2 configured with bucket 50.

And finally the rest of the items are configured with bucket 56.

Looking for query to select transaction with combo:-

Transaction include = 1 item (49) and 1 item (56)

or

Transaction include = 1 item (50) and 1 item (56)

This is what I have tried

```<code>**`select
    INVENTTABLE.[COSTGROUPID],
    INVENTTABLE.[NAMEALIAS],
    #temp_whatIWantForRealsThisTime.STORE,
    #temp_whatIWantForRealsThisTime.TRANSACTIONID,
    sum(#temp_whatIWantForRealsThisTime.PRICE) as Transaction_Sum
from #temp_whatIWantForRealsThisTime
join INVENTTABLE
    on INVENTTABLE.[ITEMID] = #temp_whatIWantForRealsThisTime.[ITEMID]
where [COSTGROUPID] in ('56', '49', '50')
and cast(#temp_whatIWantForRealsThisTime.TRANSDATE as date) between '2019-01-01' and '2019-05-28'
and #temp_whatIWantForRealsThisTime.ITEMID in ('I00075431', 'I00075432')
group by INVENTTABLE.[COSTGROUPID],
    INVENTTABLE.[NAMEALIAS],
    #temp_whatIWantForRealsThisTime.STORE,
    #temp_whatIWantForRealsThisTime.TRANSACTION_ID
order by Transaction_Sum desc;`**
</code>```

Every transaction that I look up has only item figuration bucket for either 56 or 49 or 50.

But not combination

Transaction includes = 1 item (49) and 1 item (56)

or

Transaction includes = 1 item (50) and 1 item (56)

答:
try below - </p>

```<code>select
    INVENTTABLE.[COSTGROUPID],
    INVENTTABLE.[NAMEALIAS],
    #temp_whatIWantForRealsThisTime.STORE,
    #temp_whatIWantForRealsThisTime.TRANSACTIONID,
    sum(#temp_whatIWantForRealsThisTime.PRICE) as Transaction_Sum
from #temp_whatIWantForRealsThisTime
join INVENTTABLE
    on INVENTTABLE.[ITEMID] = #temp_whatIWantForRealsThisTime.[ITEMID]
where ([COSTGROUPID] ='56' AND [COSTGROUPID] ='49' AND [COSTGROUPID] ='50')
and cast(#temp_whatIWantForRealsThisTime.TRANSDATE as date) between '2019-01-01' and '2019-05-28'
and #temp_whatIWantForRealsThisTime.ITEMID in ('I00075431', 'I00075432')

UNION ALL

select
    INVENTTABLE.[COSTGROUPID],
    INVENTTABLE.[NAMEALIAS],
    #temp_whatIWantForRealsThisTime.STORE,
    #temp_whatIWantForRealsThisTime.TRANSACTIONID,
    sum(#temp_whatIWantForRealsThisTime.PRICE) as Transaction_Sum
from #temp_whatIWantForRealsThisTime
join INVENTTABLE
    on INVENTTABLE.[ITEMID] = #temp_whatIWantForRealsThisTime.[ITEMID]
where ([COSTGROUPID] ='56' AND [COSTGROUPID] ='50')
and cast(#temp_whatIWantForRealsThisTime.TRANSDATE as date) between '2019-01-01' and '2019-05-28'
and #temp_whatIWantForRealsThisTime.ITEMID in ('I00075431', 'I00075432')

UNION ALL

select
        INVENTTABLE.[COSTGROUPID],
        INVENTTABLE.[NAMEALIAS],
        #temp_whatIWantForRealsThisTime.STORE,
        #temp_whatIWantForRealsThisTime.TRANSACTIONID,
        sum(#temp_whatIWantForRealsThisTime.PRICE) as Transaction_Sum
    from #temp_whatIWantForRealsThisTime
    join INVENTTABLE
        on INVENTTABLE.[ITEMID] = #temp_whatIWantForRealsThisTime.[ITEMID]
    where ([COSTGROUPID] ='49' AND [COSTGROUPID] ='50')
    and cast(#temp_whatIWantForRealsThisTime.TRANSDATE as date) between '2019-01-01' and '2019-05-28'
    and #temp_whatIWantForRealsThisTime.ITEMID in ('I00075431', 'I00075432')

UNION ALL

select
        INVENTTABLE.[COSTGROUPID],
        INVENTTABLE.[NAMEALIAS],
        #temp_whatIWantForRealsThisTime.STORE,
        #temp_whatIWantForRealsThisTime.TRANSACTIONID,
        sum(#temp_whatIWantForRealsThisTime.PRICE) as Transaction_Sum
    from #temp_whatIWantForRealsThisTime
    join INVENTTABLE
        on INVENTTABLE.[ITEMID] = #temp_whatIWantForRealsThisTime.[ITEMID]
    where ([COSTGROUPID] ='56' AND [COSTGROUPID] ='49')
    and cast(#temp_whatIWantForRealsThisTime.TRANSDATE as date) between '2019-01-01' and '2019-05-28'
    and #temp_whatIWantForRealsThisTime.ITEMID in ('I00075431', 'I00075432')

group by INVENTTABLE.[COSTGROUPID],
    INVENTTABLE.[NAMEALIAS],
    #temp_whatIWantForRealsThisTime.STORE,
    #temp_whatIWantForRealsThisTime.TRANSACTION_ID
order by Transaction_Sum desc;
</code>```

Body:
I need a query that can return a transaction that has multiple items. The transaction must have multiple items that belong to a combination of the buckets below:

100 Items are grouped into three buckets. Bucket 49, bucket 50, and bucket 56.

There is item 1 configured with bucket 49.

There is a item 2 configured with bucket 50.

And finally the rest of the items are configured with bucket 56.

Looking for query to select transaction with combo:-

Transaction include = 1 item (49) and 1 item (56)

or

Transaction include = 1 item (50) and 1 item (56)

This is what I have tried

**`select
    INVENTTABLE.[COSTGROUPID],
    INVENTTABLE.[NAMEALIAS],
    #temp_whatIWantForRealsThisTime.STORE,
    #temp_whatIWantForRealsThisTime.TRANSACTIONID,
    sum(#temp_whatIWantForRealsThisTime.PRICE) as Transaction_Sum
from #temp_whatIWantForRealsThisTime
join INVENTTABLE
    on INVENTTABLE.[ITEMID] = #temp_whatIWantForRealsThisTime.[ITEMID]
where [COSTGROUPID] in ('56', '49', '50')
and cast(#temp_whatIWantForRealsThisTime.TRANSDATE as date) between '2019-01-01' and '2019-05-28'
and #temp_whatIWantForRealsThisTime.ITEMID in ('I00075431', 'I00075432')
group by INVENTTABLE.[COSTGROUPID],
    INVENTTABLE.[NAMEALIAS],
    #temp_whatIWantForRealsThisTime.STORE,
    #temp_whatIWantForRealsThisTime.TRANSACTION_ID
order by Transaction_Sum desc;`**

Every transaction that I look up has only item figuration bucket for either 56 or 49 or 50.

But not combination

Transaction includes = 1 item (49) and 1 item (56)

or

Transaction includes = 1 item (50) and 1 item (56)

Body:
try below -

select
    INVENTTABLE.[COSTGROUPID],
    INVENTTABLE.[NAMEALIAS],
    #temp_whatIWantForRealsThisTime.STORE,
    #temp_whatIWantForRealsThisTime.TRANSACTIONID,
    sum(#temp_whatIWantForRealsThisTime.PRICE) as Transaction_Sum
from #temp_whatIWantForRealsThisTime
join INVENTTABLE
    on INVENTTABLE.[ITEMID] = #temp_whatIWantForRealsThisTime.[ITEMID]
where ([COSTGROUPID] ='56' AND [COSTGROUPID] ='49' AND [COSTGROUPID] ='50')
and cast(#temp_whatIWantForRealsThisTime.TRANSDATE as date) between '2019-01-01' and '2019-05-28'
and #temp_whatIWantForRealsThisTime.ITEMID in ('I00075431', 'I00075432')

UNION ALL

select
    INVENTTABLE.[COSTGROUPID],
    INVENTTABLE.[NAMEALIAS],
    #temp_whatIWantForRealsThisTime.STORE,
    #temp_whatIWantForRealsThisTime.TRANSACTIONID,
    sum(#temp_whatIWantForRealsThisTime.PRICE) as Transaction_Sum
from #temp_whatIWantForRealsThisTime
join INVENTTABLE
    on INVENTTABLE.[ITEMID] = #temp_whatIWantForRealsThisTime.[ITEMID]
where ([COSTGROUPID] ='56' AND [COSTGROUPID] ='50')
and cast(#temp_whatIWantForRealsThisTime.TRANSDATE as date) between '2019-01-01' and '2019-05-28'
and #temp_whatIWantForRealsThisTime.ITEMID in ('I00075431', 'I00075432')

UNION ALL

select
        INVENTTABLE.[COSTGROUPID],
        INVENTTABLE.[NAMEALIAS],
        #temp_whatIWantForRealsThisTime.STORE,
        #temp_whatIWantForRealsThisTime.TRANSACTIONID,
        sum(#temp_whatIWantForRealsThisTime.PRICE) as Transaction_Sum
    from #temp_whatIWantForRealsThisTime
    join INVENTTABLE
        on INVENTTABLE.[ITEMID] = #temp_whatIWantForRealsThisTime.[ITEMID]
    where ([COSTGROUPID] ='49' AND [COSTGROUPID] ='50')
    and cast(#temp_whatIWantForRealsThisTime.TRANSDATE as date) between '2019-01-01' and '2019-05-28'
    and #temp_whatIWantForRealsThisTime.ITEMID in ('I00075431', 'I00075432')

UNION ALL

select
        INVENTTABLE.[COSTGROUPID],
        INVENTTABLE.[NAMEALIAS],
        #temp_whatIWantForRealsThisTime.STORE,
        #temp_whatIWantForRealsThisTime.TRANSACTIONID,
        sum(#temp_whatIWantForRealsThisTime.PRICE) as Transaction_Sum
    from #temp_whatIWantForRealsThisTime
    join INVENTTABLE
        on INVENTTABLE.[ITEMID] = #temp_whatIWantForRealsThisTime.[ITEMID]
    where ([COSTGROUPID] ='56' AND [COSTGROUPID] ='49')
    and cast(#temp_whatIWantForRealsThisTime.TRANSDATE as date) between '2019-01-01' and '2019-05-28'
    and #temp_whatIWantForRealsThisTime.ITEMID in ('I00075431', 'I00075432')

group by INVENTTABLE.[COSTGROUPID],
    INVENTTABLE.[NAMEALIAS],
    #temp_whatIWantForRealsThisTime.STORE,
    #temp_whatIWantForRealsThisTime.TRANSACTION_ID
order by Transaction_Sum desc;


问:
Running python unit tests as part of bamboo build
I need to run python units test cases as part of bamboo build step and the build needs to fail if unit tests fail.

For this, I have a Script step in bamboo build and i am trying to run the following in it:

```<code>python -m unittest discover /test
</code>```

Here, /test folder has all the unit tests.
The output of the above script it

```<code>Ran (0) tests
</code>```

So the problem is that bamboo isn't able to discover these tests. Bamboo agent is linux.

Wondering if anyone has done such a thing before and has any suggestions.

答:
If you haven't figured it out, likely because in windows filenames aren't case sensitive but in Linux they are...

And you're test file named Test_xxxx.py isn't the same as test_xxxx.py which is the pattern that discovery is trying to use...

Body:
I need to run python units test cases as part of bamboo build step and the build needs to fail if unit tests fail.

For this, I have a Script step in bamboo build and i am trying to run the following in it:

python -m unittest discover /test

Here, /test folder has all the unit tests.
The output of the above script it

Ran (0) tests

So the problem is that bamboo isn't able to discover these tests. Bamboo agent is linux.

Wondering if anyone has done such a thing before and has any suggestions.


问:
How to duplicate a MySQL database on the same server
I have a large MySQL database, lets call it live_db, which I want to replicate on the same machine to provide a test system to play around with (test_db), including table structure and data.
In regular intervals I want to update the test_db with the content of the live_db; if possible incremental.

Is there some built-in mechanism in MySQL to do that? I think that master-slave replication is not the thing I want since it should be possible to alter data in the test_db. These changes do not have to be preserved, though.

Regards,

CGD

答: For all the mac users, with sequel pro all you need to do is go to database (menu) -> Duplicate database. Done!</p>


问:
Converting a string pattern of format 1/1/2010 3:23:12 PM +00:00 to a Java.util.Date
I am trying to convert a String with format 1/1/2010 3:23:12 PM +00:00 to a Java.util.Date

Unable to convert the String format to a Java Date.
It is not identifying the time asAM/PM

```<code>String s = "1/1/2010 3:23:12 PM +00:00";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss a",Locale.ENGLISH);

Date date = sdf.parse(s));
</code>```

Need the date converted with time identified as AM/PM

答:
OffsetDateTime is what you're looking for.

```<code>DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyyy h:mm:ss a XXX");
OffsetDateTime time = OffsetDateTime.parse(str, formatter);
System.out.println(time);
</code>```

Your pattern has some problems:

Your day-of-the-month is without a leading zero, yet you are using dd;

Same for month with MM;

Same for hour with HH;

You are using AM/PM in conjunction with a 24-hour hour format specifier (H); you should use h instead.

I don't know exactly how SimpleDateFormat handles the timezone part of the string, but no formatting specifiers for the timezone are given.

That's one of the reasons why I like this Date and Time API: it's pretty straightforward.

Ideone example

Body:
I am trying to convert a String with format 1/1/2010 3:23:12 PM +00:00 to a Java.util.Date

Unable to convert the String format to a Java Date.
It is not identifying the time asAM/PM

String s = "1/1/2010 3:23:12 PM +00:00";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss a",Locale.ENGLISH);

Date date = sdf.parse(s));

Need the date converted with time identified as AM/PM

Body:
OffsetDateTime is what you're looking for.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyyy h:mm:ss a XXX");
OffsetDateTime time = OffsetDateTime.parse(str, formatter);
System.out.println(time);

Your pattern has some problems:

Your day-of-the-month is without a leading zero, yet you are using dd;

Same for month with MM;

Same for hour with HH;

You are using AM/PM in conjunction with a 24-hour hour format specifier (H); you should use h instead.

I don't know exactly how SimpleDateFormat handles the timezone part of the string, but no formatting specifiers for the timezone are given.

That's one of the reasons why I like this Date and Time API: it's pretty straightforward.

Ideone example


问:
Why late init var cannot be used with Nullable?
Why can't we use lateinit with nullable variables?

```<code>lateinit var v: String?
</code>```

lateinit modifier is not allowed on properties of nullable types

答:
As stated in the documentation, lateinit specializes on non-nullable properties:

Normally, properties declared as having a non-null type must be initialized in the constructor. However, fairly often this is not convenient. For example, properties can be initialized through dependency injection, or in the setup method of a unit test. In this case, you cannot supply a non-null initializer in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class.

Also, if you take a look at the byte code of such a lateinit property, you see that the compiler adds a code block to ensure that this property has been initialized when being accessed. For lateinit properties, null indicates the properties initial but invalid state.

```<code>class WithLateInit {
    lateinit var something : String
}
</code>```

becomes

```<code>public final class WithLateInit {
   @NotNull
   public String something;

   @NotNull
   public final String getSomething() {
      String var10000 = this.something;
      if (var10000 == null) { // <- here you can see the lateinit check
         Intrinsics.throwUninitializedPropertyAccessException("something");
      }

      return var10000;
   }

  //setter
}
</code>```

Body:
Why can't we use lateinit with nullable variables?

lateinit var v: String?

lateinit modifier is not allowed on properties of nullable types

Body:
As stated in the documentation, lateinit specializes on non-nullable properties:

Normally, properties declared as having a non-null type must be initialized in the constructor. However, fairly often this is not convenient. For example, properties can be initialized through dependency injection, or in the setup method of a unit test. In this case, you cannot supply a non-null initializer in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class.

Also, if you take a look at the byte code of such a lateinit property, you see that the compiler adds a code block to ensure that this property has been initialized when being accessed. For lateinit properties, null indicates the properties initial but invalid state.

class WithLateInit {
    lateinit var something : String
}

becomes

public final class WithLateInit {
   @NotNull
   public String something;

   @NotNull
   public final String getSomething() {
      String var10000 = this.something;
      if (var10000 == null) { // <- here you can see the lateinit check
         Intrinsics.throwUninitializedPropertyAccessException("something");
      }

      return var10000;
   }

  //setter
}