问:
Matplotlib : how to make appear and increase the size of minor and major ticks on x logscale axis
I am working on the plot of a (logscale,symlog) data. I have difficulties to make appear on x axis (logscale) the  minor ticks with a visible height and width.

In x axis, I have values starting from 1e-8 to 1. At the beginning, because of a reason that I don't know, I had only a "2 power 10th" interval, i.e I was getting on the plot of x_axis the values of majors like this :

```<code>[1e-8, 1e-6, 1e-4, 1e-2, 1]
</code>```

I fixed this by doing explicitly :

```<code>  # Important otherwise missing ticks
  plt.xticks([1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1])
</code>```

So now, I have the following figure :

As you can see, the minor ticks for each power 10 are missing and I don't know to make them display, even there is not a lot of space between each 10 power.

Here's the code I am using to generate this figure :

```<code># Modules import
import sys
import numpy as np
import scipy.integrate as pyint
import os
from os import path
import glob
import scipy
import re
import shutil
import matplotlib.pyplot as plt
from matplotlib import ticker

# Initialize figure
fig = plt.figure(num=None, figsize=(12, 12), facecolor='w', edgecolor='k')
fig.patch.set_facecolor('white')
fig.patch.set_alpha(1)

# Control on graphic
ax = plt.gca()

# Increase space between x-axis and x-label
ax.tick_params(axis = 'x', which = 'major', pad = 15)

# Lebels on axis
plt.xlabel('Step $\Omega_{m}$', fontsize = 20)
plt.ylabel('$C_{\ell}^{\'}$($\Omega_{m}$) relative', fontsize = 20)
plt.xticks(fontsize = 20)
plt.yticks(fontsize = 20)
plt.xscale('log')
plt.grid()

# Important otherwise missing ticks
plt.xticks([1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1])

# Title : different multipoles
string_intel = '(CAMB-0.1.7) - '+type_GG_LL_GL+' - $C_{\ell}^{\'}$ relative of '+paramLatexArray[idParam]+'('+str(der)+' pts) at $z$ = '+str(zrange[idRedshift])+' - '+str(numel)+' pts'
plt.title(string_intel, fontsize = 20, pad = 25)

colorSimplePlot = ['b', 'r', 'g', 'k', 'y', 'm', 'c']

# Plot command
for idMultipole in range(len(multipole)):
  plt.plot(stepNewArray[:], eval('matrixCl_der_'+str(der)+'[:, idMultipole, idParam, lx, ly]'), colorSimplePlot[idMultipole])

# Chose if negative or positive derivatives
# Plot with symlog or log along y-axis
# 1) For example : GG at z = 2.038 and l = 366
#    needs symlog with lintreshy = 1e-9
# 2) For example : LL at z = 2.038 and l = 366
#    needs nothing (even no log)
if (type_GG_LL_GL == 'GG'):
  plt.yscale('symlog', linthreshy = 1e-9)
elif (type_GG_LL_GL == 'LL'):
  plt.yscale('linear')

# Legend
plt.legend(['$l = 366.42$', '$l = 1079.28$', '$l = 1792.14$', '$l = 2505$',\
        '$l = 3217.85$', '$l = 3930.71$', '$l = 4643.57$'], fontsize=15, loc='best')

# Save plot
plt.savefig('Cl_derivative_Omega_m.pdf')
</code>```

Anyone could see what I have got to do to display the minor xticks for each interval of the x axis logscale ?

I tried also by adding :

```<code>from matplotlib import ticker
from matplotlib.ticker import LogLocator

ax.tick_params(axis = 'x', which = 'major', pad = 15)
ax.xaxis.set_major_locator(LogLocator(base=10))
ax.xaxis.set_major_locator(LogLocator(base=10, subs=[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0]))
</code>```

But this doesn't work ...

In a second time, I would like also to have the control on the size of these minor ticks.

Thanks to @Quand Huang, I managed to do the following figure :

You can notice that Major ticks have disappeared and also the grid command, i.e by doing in my code snippet :

```<code>  minors = (0.1**np.arange(9)[:,None] * np.arange(0.1,1,0.1)).ravel()
  plt.yticks(fontsize = 20)
  plt.xscale('log')
  # Important otherwise missing ticks
  plt.xticks([1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1], fontsize = 40)
  plt.xticks(minors, fontsize = 20)
  plt.grid()
</code>```

I tried to set a large font for manual major ticks (fontsize = 40) but it doesn't appear. By the way, why did grid mode disappear ?

答:
You could generate the minor ticks like this:

```<code>minors = (0.1**np.arange(9)[:,None] * np.arange(0.1,1,0.1)).ravel()

plt.xscale('log')
plt.xticks(minors);
</code>```

Output:

Body:
I am working on the plot of a (logscale,symlog) data. I have difficulties to make appear on x axis (logscale) the  minor ticks with a visible height and width.

In x axis, I have values starting from 1e-8 to 1. At the beginning, because of a reason that I don't know, I had only a "2 power 10th" interval, i.e I was getting on the plot of x_axis the values of majors like this :

[1e-8, 1e-6, 1e-4, 1e-2, 1]

I fixed this by doing explicitly :

  # Important otherwise missing ticks
  plt.xticks([1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1])

So now, I have the following figure :

As you can see, the minor ticks for each power 10 are missing and I don't know to make them display, even there is not a lot of space between each 10 power.

Here's the code I am using to generate this figure :

# Modules import
import sys
import numpy as np
import scipy.integrate as pyint
import os
from os import path
import glob
import scipy
import re
import shutil
import matplotlib.pyplot as plt
from matplotlib import ticker

# Initialize figure
fig = plt.figure(num=None, figsize=(12, 12), facecolor='w', edgecolor='k')
fig.patch.set_facecolor('white')
fig.patch.set_alpha(1)

# Control on graphic
ax = plt.gca()

# Increase space between x-axis and x-label
ax.tick_params(axis = 'x', which = 'major', pad = 15)

# Lebels on axis
plt.xlabel('Step $\Omega_{m}$', fontsize = 20)
plt.ylabel('$C_{\ell}^{\'}$($\Omega_{m}$) relative', fontsize = 20)
plt.xticks(fontsize = 20)
plt.yticks(fontsize = 20)
plt.xscale('log')
plt.grid()

# Important otherwise missing ticks
plt.xticks([1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1])

# Title : different multipoles
string_intel = '(CAMB-0.1.7) - '+type_GG_LL_GL+' - $C_{\ell}^{\'}$ relative of '+paramLatexArray[idParam]+'('+str(der)+' pts) at $z$ = '+str(zrange[idRedshift])+' - '+str(numel)+' pts'
plt.title(string_intel, fontsize = 20, pad = 25)

colorSimplePlot = ['b', 'r', 'g', 'k', 'y', 'm', 'c']

# Plot command
for idMultipole in range(len(multipole)):
  plt.plot(stepNewArray[:], eval('matrixCl_der_'+str(der)+'[:, idMultipole, idParam, lx, ly]'), colorSimplePlot[idMultipole])

# Chose if negative or positive derivatives
# Plot with symlog or log along y-axis
# 1) For example : GG at z = 2.038 and l = 366
#    needs symlog with lintreshy = 1e-9
# 2) For example : LL at z = 2.038 and l = 366
#    needs nothing (even no log)
if (type_GG_LL_GL == 'GG'):
  plt.yscale('symlog', linthreshy = 1e-9)
elif (type_GG_LL_GL == 'LL'):
  plt.yscale('linear')

# Legend
plt.legend(['$l = 366.42$', '$l = 1079.28$', '$l = 1792.14$', '$l = 2505$',\
        '$l = 3217.85$', '$l = 3930.71$', '$l = 4643.57$'], fontsize=15, loc='best')

# Save plot
plt.savefig('Cl_derivative_Omega_m.pdf')

Anyone could see what I have got to do to display the minor xticks for each interval of the x axis logscale ?

I tried also by adding :

from matplotlib import ticker
from matplotlib.ticker import LogLocator

ax.tick_params(axis = 'x', which = 'major', pad = 15)
ax.xaxis.set_major_locator(LogLocator(base=10))
ax.xaxis.set_major_locator(LogLocator(base=10, subs=[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0]))

But this doesn't work ...

In a second time, I would like also to have the control on the size of these minor ticks.

Thanks to @Quand Huang, I managed to do the following figure :

You can notice that Major ticks have disappeared and also the grid command, i.e by doing in my code snippet :

  minors = (0.1**np.arange(9)[:,None] * np.arange(0.1,1,0.1)).ravel()
  plt.yticks(fontsize = 20)
  plt.xscale('log')
  # Important otherwise missing ticks
  plt.xticks([1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1], fontsize = 40)
  plt.xticks(minors, fontsize = 20)
  plt.grid()

I tried to set a large font for manual major ticks (fontsize = 40) but it doesn't appear. By the way, why did grid mode disappear ?

Body:
You could generate the minor ticks like this:

minors = (0.1**np.arange(9)[:,None] * np.arange(0.1,1,0.1)).ravel()

plt.xscale('log')
plt.xticks(minors);

Output:


来源: stackexchange

问:
HTML notification on button press
I'm working on a buzzer app that when the user enters the site it alerts them to input there name into the alert box then when they press the button i want it to tell me there name i dont care about how to get this if its by a online database or via text or email as long it is only that button that needs to be presssed.

ive tryed using firebase but found it too confussing so if anyone can explain it in a way i can understand that could also solve this problem

```<code><html>
<head>

  <title>Buzzer Page</title>

  <link rel="stylesheet" href="styles.css"></link>

  <script type="text/javascript" src="script.js"></script>

  <link rel="icon" href="Clever person.jpg" type="image/jpg">

  <meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>

  <main>
    <div class="center">
      <button id="buzzingButton" onclick="buzz()"><img src="Clever person.jpg" width="100px"</img><br><h1>Press To Buzz</h1></button>
    </div>
  </main>

</body>
</html>
</code>```

now my css

```<code>body {
  background-image: url('https://cdn.lowgif.com/full/c3a75154a9816ee0-wallpaper-gif-by-matthew-butler-find-share-on-giphy.gif');
  background-size: cover;
}

h1 {
  color: lightgreen;
}

.center {
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

#buzzingbutton {
  padding: 15px 25px;
  font-size: 24px;
  text-align: center;
  cursor: pointer;
  outline: none;
  color: #fff;
  background-color: #4CAF50;
  border: none;
  border-radius: 15px;
  box-shadow: 0 9px #999;
  width: 700px;
  height:auto;
}

#buzzingbutton:hover {background-color: #3e8e41}

#buzzingButton:active {
  background-color: #3e8e41;
  box-shadow: 0 5px #666;
  transform: translateY(4px);

}
</code>```

now my javascript

```<code>

var name = prompt("Please enter your name so we know who pressed the buzzer","<ENTER NAME HERE>")

var snd = new Audio("Buzzer-sound.mp3");

function buzz() {
  snd.play();
  snd.currentTime=0
  })
}

</code>```

many thanks

答:
```<code><!--html-->
<input type="text" id="name">
 <button onclick = "buzz()">PressMe</button>

<!--Javascript-->
function buzz(){
    var name = document.getElementById("name");
    var displayName = name.value;
    alert(displayName);
}
</code>```

That should do the trick, to display alerts just use the alert(); function. You can also include text in it by simply doing alert("Insert text here");. Hope this works for you :)

ContentLicense: CC BY-SA 4.0

Title: HTML notification on button press

Body:
I'm working on a buzzer app that when the user enters the site it alerts them to input there name into the alert box then when they press the button i want it to tell me there name i dont care about how to get this if its by a online database or via text or email as long it is only that button that needs to be presssed.

ive tryed using firebase but found it too confussing so if anyone can explain it in a way i can understand that could also solve this problem

  <title>Buzzer Page</title>

  <link rel="stylesheet" href="styles.css"></link>

  <link rel="icon" href="Clever person.jpg" type="image/jpg">

  <meta name="viewport" content="width=device-width, initial-scale=1">

      <button id="buzzingButton" onclick="buzz()"><img src="Clever person.jpg" width="100px"

Press To Buzz
</button>

now my css

body {
  background-image: url('https://cdn.lowgif.com/full/c3a75154a9816ee0-wallpaper-gif-by-matthew-butler-find-share-on-giphy.gif');
  background-size: cover;
}

h1 {
  color: lightgreen;
}

.center {
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

#buzzingbutton {
  padding: 15px 25px;
  font-size: 24px;
  text-align: center;
  cursor: pointer;
  outline: none;
  color: #fff;
  background-color: #4CAF50;
  border: none;
  border-radius: 15px;
  box-shadow: 0 9px #999;
  width: 700px;
  height:auto;
}

#buzzingbutton:hover {background-color: #3e8e41}

#buzzingButton:active {
  background-color: #3e8e41;
  box-shadow: 0 5px #666;
  transform: translateY(4px);

}

now my javascript

var name = prompt("Please enter your name so we know who pressed the buzzer","<ENTER NAME HERE>")

var snd = new Audio("Buzzer-sound.mp3");

function buzz() {
  snd.play();
  snd.currentTime=0
  })
}

many thanks

Body:
<!--html-->
<input type="text" id="name">
 <button onclick = "buzz()">PressMe</button>

<!--Javascript-->
function buzz(){
    var name = document.getElementById("name");
    var displayName = name.value;
    alert(displayName);
}

That should do the trick, to display alerts just use the alert(); function. You can also include text in it by simply doing alert("Insert text here");. Hope this works for you :)


问:
Unable to build a Q# program in VS Code
I am new to quantum computing and have just installed Microsoft's Visual Studio Code and the QDK extension for it. However, when I try to build and run (dotnet run from the terminal), it is unable to give me an output for it and throws a few errors regarding namespace despite installing the extension (quantum sdk). I'm most likely doing something stupid so please point me in the right direction

My program is:

```<code>namespace helloqworld {

    open Microsoft.Quantum.Canon;
    open Microsoft.Quantum.Intrinsic;

    @EntryPoint()
    operation HelloQ() : Unit {
        Message("Hello quantum world!");
    }
}
</code>```

And I get the following errors:

```<code>No namespace with the name "Microsoft.Quantum.Canon" exists.
No namespace with the name "Microsoft.Quantum.Intrinsic" exists.
{
    "resource": "/Users/nalini/Desktop/helloqworld/Program.qs",
    "owner": "_generated_diagnostic_collection_name_#0",
    "code": "QS6005",
    "severity": 8,
    "message": "No type with the name \"EntryPoint\" exists in any of the open namespaces.",
    "source": "/Users/nalini/Desktop/helloqworld/Program.qs",
    "startLineNumber": 9,
    "startColumn": 6,
    "endLineNumber": 9,
    "endColumn": 16
}
{
    "resource": "/Users/nalini/Desktop/helloqworld/Program.qs",
    "owner": "_generated_diagnostic_collection_name_#0",
    "code": "QS5022",
    "severity": 8,
    "message": "No identifier with the name \"Message\" exists.",
    "source": "/Users/nalini/Desktop/helloqworld/Program.qs",
    "startLineNumber": 11,
    "startColumn": 9,
    "endLineNumber": 11,
    "endColumn": 16
}
</code>```

And my csproj file has:

```<code>Project Sdk="Microsoft.Quantum.Sdk/0.11.2004.2825">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

</Project>
</code>```

答:
Does your code build and run successfully if you just do dotnet run from terminal? If this is the case, this error comes from IntelliSense.

Are you using .NET Core 3.1.300? I think QDK release 0.11.2004.2825 has IntelliSense issues with .NET Core 3.1.300 specifically (the relevant issue on GitHub), and downgrading .NET Core to 3.1.201 fixes this issue.

Title: Unable to build a Q# program in VS Code

Body:
I am new to quantum computing and have just installed Microsoft's Visual Studio Code and the QDK extension for it. However, when I try to build and run (dotnet run from the terminal), it is unable to give me an output for it and throws a few errors regarding namespace despite installing the extension (quantum sdk). I'm most likely doing something stupid so please point me in the right direction

My program is:

namespace helloqworld {

    open Microsoft.Quantum.Canon;
    open Microsoft.Quantum.Intrinsic;

    @EntryPoint()
    operation HelloQ() : Unit {
        Message("Hello quantum world!");
    }
}

And I get the following errors:

No namespace with the name "Microsoft.Quantum.Canon" exists.
No namespace with the name "Microsoft.Quantum.Intrinsic" exists.
{
    "resource": "/Users/nalini/Desktop/helloqworld/Program.qs",
    "owner": "_generated_diagnostic_collection_name_#0",
    "code": "QS6005",
    "severity": 8,
    "message": "No type with the name \"EntryPoint\" exists in any of the open namespaces.",
    "source": "/Users/nalini/Desktop/helloqworld/Program.qs",
    "startLineNumber": 9,
    "startColumn": 6,
    "endLineNumber": 9,
    "endColumn": 16
}
{
    "resource": "/Users/nalini/Desktop/helloqworld/Program.qs",
    "owner": "_generated_diagnostic_collection_name_#0",
    "code": "QS5022",
    "severity": 8,
    "message": "No identifier with the name \"Message\" exists.",
    "source": "/Users/nalini/Desktop/helloqworld/Program.qs",
    "startLineNumber": 11,
    "startColumn": 9,
    "endLineNumber": 11,
    "endColumn": 16
}

And my csproj file has:

Project Sdk="Microsoft.Quantum.Sdk/0.11.2004.2825">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

</Project>


问:
Azure AD Device Registered Column
I cannot find any way to export the registered date from AAD using any Powershell commandlets.</p>

答: I learned that it is not possible to do this within powershell currently.</p>

Title: Azure AD Device Registered Column


问:
Expo Permissions returns status of 'undetermined' in Production
In my react native app which I ave published on the Google Play Store, I require Camera Roll permissions. This works during testing, but not in the published version of the app.

```<code>  getPermissionAsync = async () => {
    const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
    if (status !== "granted") {
      alert("Sorry, we need camera roll permissions to make this work!");
    }
    await this.setState({ permission: status === "granted" });
  };

  _pickMedia = async () => {
    if (this.state.permission != true) {
      await this.getPermissionAsync();
    }
    if (this.state.permission == true) {
        // get image
    }
  };
</code>```

In testing this works as expected, asking permission to access the camera roll every time the user tries to upload a picture till its given. However in production, the user is prompted once for permission to use the camera roll and whether or not they allow it, the alert box comes up and the user is unable to pick an image. If they try to add media again, they aren't prompted for permissions and it just alerts again.

As per the expo docs I have added READ_EXTERNAL_STORAGE to my permissions in app.json:

```<code>    "android": {
      "permissions": ["READ_EXTERNAL_STORAGE", "WRITE_EXTERNAL_STORAGE"],
    }
</code>```

Could someone tell me why this doesn't work in production?

答: I didn't realise that edits to parts of  app.json aren't updated for a published app by expo publish and you need to run expo build instead. The issue was  that I hadn't initially added WRITE_EXTERNAL_STORAGE to the permissions and when I did later I used expo publish to update the app. This meant the published version wasn't actually updated.  After running expo build now and generating a new app bundle, permissions started working correctly.

Body:
In my react native app which I ave published on the Google Play Store, I require Camera Roll permissions. This works during testing, but not in the published version of the app.

  getPermissionAsync = async () => {
    const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
    if (status !== "granted") {
      alert("Sorry, we need camera roll permissions to make this work!");
    }
    await this.setState({ permission: status === "granted" });
  };

  _pickMedia = async () => {
    if (this.state.permission != true) {
      await this.getPermissionAsync();
    }
    if (this.state.permission == true) {
        // get image
    }
  };

In testing this works as expected, asking permission to access the camera roll every time the user tries to upload a picture till its given. However in production, the user is prompted once for permission to use the camera roll and whether or not they allow it, the alert box comes up and the user is unable to pick an image. If they try to add media again, they aren't prompted for permissions and it just alerts again.

As per the expo docs I have added READ_EXTERNAL_STORAGE to my permissions in app.json:

    "android": {
      "permissions": ["READ_EXTERNAL_STORAGE", "WRITE_EXTERNAL_STORAGE"],
    }

Could someone tell me why this doesn't work in production?


问:
Xcode on Windows
What are the disadvantage of working with Xcode on Windows? What problems do I encounter from the beginning to the end (upload to the market) of the application development process?</p>

答:
You could try using Virtual Box and Hackintosh to Virtualize a mac.
I don't know if it helps but you could try it.
https://www.virtualbox.org/

https://hackintosh.com/

Title: Xcode on Windows


问:
Displaying images encoded with base64 in react native
I am new to react native and I am trying to display images encoded with base 64.

```<code> <Image source={{uri: `data:image/png;base64,${element.img}`}}
                           style={{height: 200, width: null, flex: 1}}/>
</code>```

This is the mongoose scheme where I store my images

```<code> img: {
    data: Buffer,
    contentType: String,
},
</code>```

And this is how I save them to database (photoData contains img):

```<code>this.setState({img:data.base64})
axios.post('uri', photoData, config)
</code>```

Here is my img data : img data

data is returning back as buffer so using this

data:image/png;base64,${element.img}

is not working. I tried using Buffer.from('','base64').toString('ascii') but still, image is not showing.

答:
Your response is a buffer object you will have to use the below code to convert to base64 Image.</p>

```<code>const data = Buffer.from(response, 'binary').toString('base64');

const base64Image = `data:image/png;base64,${data}`;

and then you can use the image normally
<Image source={{uri: base64Image}}/>
</code>```

Body:
I am new to react native and I am trying to display images encoded with base 64.

 <Image source={{uri: `data:image/png;base64,${element.img}`}}
                           style={{height: 200, width: null, flex: 1}}/>

This is the mongoose scheme where I store my images

 img: {
    data: Buffer,
    contentType: String,
},

And this is how I save them to database (photoData contains img):

this.setState({img:data.base64})
axios.post('uri', photoData, config)

Here is my img data : img data

data is returning back as buffer so using this

data:image/png;base64,${element.img}

is not working. I tried using Buffer.from('','base64').toString('ascii') but still, image is not showing.

Body:
Your response is a buffer object you will have to use the below code to convert to base64 Image.

const data = Buffer.from(response, 'binary').toString('base64');

const base64Image = `data:image/png;base64,${data}`;

and then you can use the image normally
<Image source={{uri: base64Image}}/>


问:
How to put multiple project_number/sender id in google-services.json
I want to be able to add more than one sender id in my android app.

From https://developers.google.com/cloud-messaging/concept-options

GCM allows multiple parties to send messages to the same client app. For example, suppose the client app is an articles aggregator with multiple contributors, and each of them should be able to send a message when they publish a new article. This message might contain a URL so that the client app can download the article. Instead of having to centralize all sending activity in one location, GCM gives you the ability to let each of these contributors send its own messages.

How is this achieved using google-services.json configuration file?

答:
Comma seperated senderID solution is still working and able to register same token for 2 different sender. I sent push notif to that single magical token with using 2 different api key and able to receive push notifs for both api key. Hope it works at least till the end of 2020. Because I'm trying to make a seamless transition between an old GCM and FCM projects which targets more than 1 million user. (hear me google and thank you google for not deprecating this great solution)

String magicalToken = FirebaseInstanceId.getInstance().getToken("senderId, anotherSenderId", "FCM");

ContentLicense: CC BY-SA 3.0


问:
Sys.WebForms.PageRequestManager pageLoaded event caching function?
I've got a master page that contains this code at the bottom of the page:

```<code><script type="text/javascript">
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(closeLoading);
    Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(parseData);
</script>
</form>
</code>```

the parseData() function I'm creating inside the main page and I'm adding functions to it based on each page load.  parseData IS called after every AJAX refresh, but it appears to only call the contents of the function from BEFORE the request.  If I hit F5 to refresh the page again, it will properly call all of the newly added content in the parseData function.

Does this function cache that data?  How can I make sure it calls the newly created contents of the parseData function?

答: According to the research I did, this is a problem with MS AJAX UpdatePanels and you are really better off not using them.  I revised my JavaScript to pull data from hidden form fields instead so the JavaScript functions never changed and was able to get this working.</p>

Body:
I've got a master page that contains this code at the bottom of the page:

</form>

the parseData() function I'm creating inside the main page and I'm adding functions to it based on each page load.  parseData IS called after every AJAX refresh, but it appears to only call the contents of the function from BEFORE the request.  If I hit F5 to refresh the page again, it will properly call all of the newly added content in the parseData function.

Does this function cache that data?  How can I make sure it calls the newly created contents of the parseData function?


问:
Validating input value from console without exiting loop C#
Lets say for a console application, I want the user to enter how many dices he would like to throw. Onlu values 1-5 will be accepted. I tried doing this:

```<code>Console.WriteLine("How many dices would you like to throw?");
int amount = Convert.ToInt32(Console.ReadLine());

while(true)
{
 if(amount < 1 || amount > 5)
 {
     Console.WriteLine("Please enter a value between 1-5");
     break;
 }
}
</code>```

The problem here is that if the user enters an invalid number, the program stops. I want it to simply continue asking until correct value is inputed. Any ideas?

cheers.

答:
You might want to check if the entered value is actually an integer.

```<code>        int amount;
        Console.WriteLine("How many dices would you like to throw?");
        do
        {
            if (int.TryParse(Console.ReadLine(), out var i))
            {
                if (i >= 1 && i <= 5)
                {
                    amount = i;
                    break;
                }
                Console.WriteLine("The integer value is not between 1 and 5");
            }
            {
                Console.WriteLine("The value you entered is not an integer");
            }
        } while (true);
</code>```

EDIT

I generally like to give the user the option to exit completely.

```<code>        int amount;
        Console.WriteLine("How many dices would you like to throw? Or enter 'X' to exit.");
        do
        {
            var input = Console.ReadLine();
            if(input.Equals("X", StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            if (int.TryParse(input, out var i))
            {
                if (i >= 1 && i <= 5)
                {
                    amount = i;
                    break;
                }
                Console.WriteLine("The integer value is not between 1 and 5");
            }
            {
                Console.WriteLine("The value you entered is not an integer");
            }
        } while (true);
</code>```

Body:
Lets say for a console application, I want the user to enter how many dices he would like to throw. Onlu values 1-5 will be accepted. I tried doing this:

Console.WriteLine("How many dices would you like to throw?");
int amount = Convert.ToInt32(Console.ReadLine());

while(true)
{
 if(amount < 1 || amount > 5)
 {
     Console.WriteLine("Please enter a value between 1-5");
     break;
 }
}

The problem here is that if the user enters an invalid number, the program stops. I want it to simply continue asking until correct value is inputed. Any ideas?

cheers.

Body:
You might want to check if the entered value is actually an integer.

        int amount;
        Console.WriteLine("How many dices would you like to throw?");
        do
        {
            if (int.TryParse(Console.ReadLine(), out var i))
            {
                if (i >= 1 && i <= 5)
                {
                    amount = i;
                    break;
                }
                Console.WriteLine("The integer value is not between 1 and 5");
            }
            {
                Console.WriteLine("The value you entered is not an integer");
            }
        } while (true);

EDIT

I generally like to give the user the option to exit completely.

        int amount;
        Console.WriteLine("How many dices would you like to throw? Or enter 'X' to exit.");
        do
        {
            var input = Console.ReadLine();
            if(input.Equals("X", StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            if (int.TryParse(input, out var i))
            {
                if (i >= 1 && i <= 5)
                {
                    amount = i;
                    break;
                }
                Console.WriteLine("The integer value is not between 1 and 5");
            }
            {
                Console.WriteLine("The value you entered is not an integer");
            }
        } while (true);


问:
If nested function in Excel
I have written the IF nested function as below, but I am getting CC for all the rows. What is wrong here.
=IF(C122="Credit Cards","CC",IF(C122="Investing","INV",IF(C122="Business","BUS",IF(C122="EDB","EDB",IF(C122="Home Loans","HL",IF(C122="Superannuation","SUP",IF(C122="Investing","INV",IF(C122="Brand","BR","PL"))))))))</p>

答:
Instead of using long nested IF() functions that are prone to errors, you can create a small table with the data you are comparing with (G3:H10 in the example below) and use INDEX():

The formula in this example is:

```<code>=INDEX($H$3:$H$10,MATCH(C13,$G$3:$G$10,0))
</code>```

Title: If nested function in Excel

Body:
Instead of using long nested IF() functions that are prone to errors, you can create a small table with the data you are comparing with (G3:H10 in the example below) and use INDEX():

The formula in this example is:

=INDEX($H$3:$H$10,MATCH(C13,$G$3:$G$10,0))


问:
Trying to combine a list of lists in python
I have a list of lists containing tuples of x and y coordinates such as
[ [(1, 2), (3, 4), (5, 6)], [(7,8), (0,5)] ] and I want to combine them in such a way where the output contains all the x coordinates together and all the y coordinates together. Essentially I'm trying to make the output be [(1,3,5,7,0), (2,4,6,8,5)] so that it is a 2xN matrix. I tried to do list(zip(*b) where b = [[(1, 2), (3, 4), (5, 6)], [(7,8), (0,5)]] (the original list), but that has not given me the correct output.

答:
Create a flat list first and then create a list of two tuples</p>

```<code>a = [[(1, 2), (3, 4), (5, 6)], [(7,8), (0,5)]]

flat_list = [item for sublist in a for item in sublist]
b = list(zip(*flat_list))
</code>```

Body:
Create a flat list first and then create a list of two tuples

a = [[(1, 2), (3, 4), (5, 6)], [(7,8), (0,5)]]

flat_list = [item for sublist in a for item in sublist]
b = list(zip(*flat_list))


问:
Python: How to affix the values of another df's columns to current df col names
I have original df:

```<code>df = pd.DataFrame({'Creatinine':[68,69,80,75],
                  'Ferritin':[251,1481,107,110],
                  'ALT':[11,14,10,15]})
</code>```

I would like to add the values of df2 (below) as a suffix to the col names of df respectively.

```<code>df2 = pd.DataFrame({'Creatinine_Units':['umol/L','umol/L','umol/L','umol/L'],
                  'Ferritin_units':['ug/L','ug/L','ug/L','ug/L'],
                  'ALT':['U/L','U/L','U/L','U/L']})
</code>```

Expected Outcome:

How do I go about this in Python?

答:
You can perform arithmetic on column names like this:

```<code>df.columns = df.columns + ' (' + df2.iloc[0] + ')'
</code>```

Output:

```<code>   Creatinine (umol/L)  Ferritin (ug/L)  ALT (U/L)
0                   68              251         11
1                   69             1481         14
2                   80              107         10
3                   75              110         15
</code>```

Body:
I have original df:

df = pd.DataFrame({'Creatinine':[68,69,80,75],
                  'Ferritin':[251,1481,107,110],
                  'ALT':[11,14,10,15]})

I would like to add the values of df2 (below) as a suffix to the col names of df respectively.

df2 = pd.DataFrame({'Creatinine_Units':['umol/L','umol/L','umol/L','umol/L'],
                  'Ferritin_units':['ug/L','ug/L','ug/L','ug/L'],
                  'ALT':['U/L','U/L','U/L','U/L']})

Expected Outcome:

How do I go about this in Python?

Body:
You can perform arithmetic on column names like this:

df.columns = df.columns + ' (' + df2.iloc[0] + ')'

Output:

   Creatinine (umol/L)  Ferritin (ug/L)  ALT (U/L)
0                   68              251         11
1                   69             1481         14
2                   80              107         10
3                   75              110         15


问:
React Native - Animation only works after Toggle Inspect on Android
I'm quite new on React/React-Native environment and I'm facing some problems with Animations on Android.

I'm using a react animation to show a bottom Alert on errors and warnings.
The problem is that the animation is working fine on iOS but only works on Android after I enable the "Toggle Inspector", if I don't enable it the animation doesn't work, on debugger I'm able to see that the component is on the React components structure.

I already tried workarounds as setting the Animated.Value to 0.01 and changing Animated.createAnimatedComponent to Animated.View.

The animation should occur after the state is changed and the visible property is set to TRUE, the change of the state is OK as I can see it working on the React Native Debbuger, and the slideIn/slideOut functions are being called by the useEffect hook.

I'm on version React 16.11.0 and React-Native 0.62.2

UPDATE

I removed position: absolute from my component and now I'm able to see the animation on the top of my screen, I've tried to change the value of z-index to a higher value (I don't have any z-index higher than 1 in my app) but it didn't worked as well.

Here is the main part of the code:

export const Alert = withTheme(({ theme: { primary, textGray } }) => {
  const translateValue = useRef(new Animated.Value(0)).current;
  const dispatch = useDispatch();
  const {
    visible,
    data: { type, message }
  } = useSelector(({ notification }) => notification);

  const slideIn = useCallback(() => {
    Animated.timing(translateValue, {
      toValue: 1,
      duration: 1000,
      useNativeDriver: true
    }).start();
  }, [translateValue]);

  const slideOut = useCallback(() => {
    Animated.timing(translateValue, {
      toValue: 0,
      duration: 1000,
      useNativeDriver: true
    }).start();
  }, [translateValue]);

  const handleClose = () => {
    dispatch(hideNotification());
  };

  useEffect(() => {
    if (visible) {
      slideIn();
    } else {
      slideOut();
    }
  }, [visible, slideIn, slideOut]);

  return (
    <Wrapper
      style={{
        transform: [
          {
            translateY: translateValue.interpolate({
              inputRange: [0, 1],
              outputRange: [300, 0]
            })
          }
        ]
      }}>
      <Content>
        <Icon name={icons[type]} size={20} color={primary} />
        <Message>{message}</Message>
      </Content>
      <Button
        onPress={handleClose}
        accessible
        accessibilityRole="button"
        accessibilityLabel="Fechar notificação">
        <Icon size={20} name="x" color={textGray} />
      </Button>
    </Wrapper>
  );
});

const Wrapper = Animated.createAnimatedComponent(styled.SafeAreaView`
  width: 100%;
  border-top-width: 1px;
  border-top-color: ${({ theme: { border } }) => border};
  background: ${({ theme: { background } }) => background};
  z-index: 1;
  position: absolute;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  bottom: 0;
  left: 0;
`);```

答:
Fixed!
It seems that there are some problems with z-index on Android.
To fix the problem I just added elevation: 1 when the Platform is Android.

See the code below:

    <Wrapper
          isAndroid={Platform.OS === 'android'}
          style={{
            transform: [
              {
                translateY: translateValue.interpolate({
                  inputRange: [0, 1],
                  outputRange: [300, 0]
                })
              }
            ]
          }}>
          <Content>
            <Icon name={icons[type]} size={20} color={primary} />
            <Message>{message}</Message>
          </Content>
          <Button
            onPress={handleClose}
            accessible
            accessibilityRole="button"
            accessibilityLabel="Fechar notificação">
            <Icon size={20} name="x" color={textGray} />
          </Button>
        </Wrapper>
      );

    const Wrapper = Animated.createAnimatedComponent(styled.SafeAreaView`
      width: 100%;
      border-top-width: 1px;
      border-top-color: ${({ theme: { border } }) => border};
      background: ${({ theme: { background } }) => background};
      z-index: 1;
      position: absolute;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      bottom: 0;
      left: 0;
      ${({ isAndroid }) => isAndroid && 'elevation: 1'}
    `);```


问:
How to get the desired outpout from the following list?
Suppose the is a list with following values

```<code>A=[1,2,3,4,5,6,7]
</code>```

The Required Output is

print

```<code>1
1+2
1+2+3
1+2+3+4
1+2+3+4+5
1+2+3+4+5+6
1+2+3+4+5+6+7
</code>```

Please help me to get the above answer..

答:
Although there can be many approaches to get the answer, you can use following code to get your answer.</p>

```<code>A = [1,2,3,4,5,6,7]
temp = A[0]
print(temp)
for x in range(1, len(A)):

    for y in range(x):
        temp = str(temp) + "+" + str(A[y+1])
    print(temp)
    temp = A[0]
</code>```

Body:
Suppose the is a list with following values

A=[1,2,3,4,5,6,7]

The Required Output is

print

1
1+2
1+2+3
1+2+3+4
1+2+3+4+5
1+2+3+4+5+6
1+2+3+4+5+6+7

Please help me to get the above answer..

Body:
Although there can be many approaches to get the answer, you can use following code to get your answer.

A = [1,2,3,4,5,6,7]
temp = A[0]
print(temp)
for x in range(1, len(A)):

    for y in range(x):
        temp = str(temp) + "+" + str(A[y+1])
    print(temp)
    temp = A[0]


问:
How do I open a file in python?
I need to read the file called, "ranks.dat", however whenever I try opening the file it says there is no such file or directory even though I have downloaded the file. Below is my code:

```<code># Reading from a file
numFile = open("ranks.dat", "r")

while True:
    text = numFile.readline()
    #rstrip removes the newline character read at the end of the line
    text = text.rstrip("\n")
    if text=="":
        break
    print (text, end = "\t")

numFile.close()
</code>```

The files should always have the following fields:
Rank - Word of Size 15 or less - the Name of the Card
Power - Integer less than 100 - the Power of the Card
Number - Integer less than 100 - the Number of these cards

I need to store each of the fields into their own list. But it does not seem to work.

答:
You need to specify the route, here are the lines.</p>

```<code>import sys
import os

ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
dir = os.path.join(ROOT_DIR, "YOURFOLDERNAME")

numFile = open(dir+'/'+"ranks.dat", "r")
</code>```

Title: How do I open a file in python?

Body:
I need to read the file called, "ranks.dat", however whenever I try opening the file it says there is no such file or directory even though I have downloaded the file. Below is my code:

# Reading from a file
numFile = open("ranks.dat", "r")

while True:
    text = numFile.readline()
    #rstrip removes the newline character read at the end of the line
    text = text.rstrip("\n")
    if text=="":
        break
    print (text, end = "\t")

numFile.close()

The files should always have the following fields:
Rank - Word of Size 15 or less - the Name of the Card
Power - Integer less than 100 - the Power of the Card
Number - Integer less than 100 - the Number of these cards

I need to store each of the fields into their own list. But it does not seem to work.

Body:
You need to specify the route, here are the lines.

import sys
import os

ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
dir = os.path.join(ROOT_DIR, "YOURFOLDERNAME")

numFile = open(dir+'/'+"ranks.dat", "r")


问:
Flask - allowing users into a group of projects, based on project being a variable and an @app.route id
I am using flask-security. I would like to set up @roles_accepted with a variable based upon the app route.

For example, if _id = Lon_2020 the @roles_accepted would allow Lon. This would grant certain users to projects, but not others, based on the _id.

```<code>@app.route('/<string:_id>')
@app.route('/<string:_id>/')
@roles_accepted('admin',_id[:3])
def home(_id):
    return redirect(url_for('tb',_id=_id))
</code>```

At the moment, this causes an error, because _id is not defined. The roles_accepted relies on the _id data.

If this is not possible, would you mind letting me know a better way of allowing certain users into certain projects. e.g.

```<code>Lon_2019
Lon_2020
Lon_2021
Par_2019
Par_2020
Par_2021
Ber_2018
Ber_2019

where the identified is the first 3 characters 'Lon','Par','Ber'
</code>```

Any help is much appreciated. Thank you.

答:
In a case like this - don't use the decorator - in your app.route - have the first couple lines calculate the 'role' then call the decorator directly such as:</p>

```<code>@app.route("/createpost")
@auth_required()
def createpost():
  /// figure out what role based on current_user or whatever
  return roles_required("author")(domyview)()

def domyview():
    // Actual code for endpoint here.
</code>```

Body:
I am using flask-security. I would like to set up @roles_accepted with a variable based upon the app route.

For example, if _id = Lon_2020 the @roles_accepted would allow Lon. This would grant certain users to projects, but not others, based on the _id.

@app.route('/<string:_id>')
@app.route('/<string:_id>/')
@roles_accepted('admin',_id[:3])
def home(_id):
    return redirect(url_for('tb',_id=_id))

At the moment, this causes an error, because _id is not defined. The roles_accepted relies on the _id data.

If this is not possible, would you mind letting me know a better way of allowing certain users into certain projects. e.g.

Lon_2019
Lon_2020
Lon_2021
Par_2019
Par_2020
Par_2021
Ber_2018
Ber_2019

where the identified is the first 3 characters 'Lon','Par','Ber'

Any help is much appreciated. Thank you.

Body:
In a case like this - don't use the decorator - in your app.route - have the first couple lines calculate the 'role' then call the decorator directly such as:

@app.route("/createpost")
@auth_required()
def createpost():
  /// figure out what role based on current_user or whatever
  return roles_required("author")(domyview)()

def domyview():
    // Actual code for endpoint here.


问:
Configuration in Android Studio - Could not find or load Main class
Am not sure what went wrong, but I am not able to execute the code in my Kotlin library any more. It's not an app with UI, but just a main class executing functions from other custom classes. Just practicing some data structures.

I noticed all the configurations were deleted when I opened AS today after upgrading my AS to 4.0. I am trying to set new config, but I am not able to select MainActivity as my main class in the config. When I run the app, I get "Could not find or load Main class" error.

Anything else that I need to set?

Below are snapshots.

答: Since it is an android app, you have to add the app module. Click on the plus button and select android App and select app as the module in it.


问:
Python: Cannot install python module "pyautogui"
I can't install python module called "pyautogui" on windows 10 with python version 3.8

CMD:

```<code>C:\Users\Миша>pip install pyautogui
Collecting pyautogui
  Using cached PyAutoGUI-0.9.50.tar.gz (57 kB)
Collecting pymsgbox
  Using cached PyMsgBox-1.0.8.tar.gz (18 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... error
    ERROR: Command errored out with exit status 1:
     command: 'c:\python38\python.exe' 'c:\python38\lib\site-packages\pip\_vendor\pep517\_in_process.py' prepare_metadata_for_build_wheel 'C:\Users\CA81~1\AppData\Local\Temp\tmphpcf9lnw'
         cwd: C:\Users\Миша\AppData\Local\Temp\pip-install-rzx8xe3p\pymsgbox
    Complete output (14 lines):
    running dist_info
    creating C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info
    writing C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\PKG-INFO
    writing dependency_links to C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\dependency_links.txt
    writing top-level names to C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\top_level.txt
    writing manifest file 'C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\SOURCES.txt'
    reading manifest file 'C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    Error in sitecustomize; set PYTHONVERBOSE for traceback:
    SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xcc in position 0: invalid continuation byte (sitecustomize.py, line 21)
    warning: no files found matching '*.py' under directory 'pymsgbox'
    writing manifest file 'C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\SOURCES.txt'
    creating 'C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.dist-info'
    error: invalid command 'bdist_wheel'
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'c:\python38\python.exe' 'c:\python38\lib\site-packages\pip\_vendor\pep517\_in_process.py' prepare_metadata_for_build_wheel 'C:\Users\CA81~1\AppData\Local\Temp\tmphpcf9lnw' Check the logs for full command output.
</code>```

I haven't tried to do something yet because I don't understand the error. Any ideas?

答:
I found the solution:

rollback pip to an older version:

```<code>python -m pip install pip==18.1
</code>```

install desired module:

```<code>pip install pyautogui
</code>```

update pip:

```<code>python -m pip install --upgrade pip
</code>```

P.S. this solution works for other modules too.

Body:
I can't install python module called "pyautogui" on windows 10 with python version 3.8

CMD:

C:\Users\Миша>pip install pyautogui
Collecting pyautogui
  Using cached PyAutoGUI-0.9.50.tar.gz (57 kB)
Collecting pymsgbox
  Using cached PyMsgBox-1.0.8.tar.gz (18 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... error
    ERROR: Command errored out with exit status 1:
     command: 'c:\python38\python.exe' 'c:\python38\lib\site-packages\pip\_vendor\pep517\_in_process.py' prepare_metadata_for_build_wheel 'C:\Users\CA81~1\AppData\Local\Temp\tmphpcf9lnw'
         cwd: C:\Users\Миша\AppData\Local\Temp\pip-install-rzx8xe3p\pymsgbox
    Complete output (14 lines):
    running dist_info
    creating C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info
    writing C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\PKG-INFO
    writing dependency_links to C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\dependency_links.txt
    writing top-level names to C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\top_level.txt
    writing manifest file 'C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\SOURCES.txt'
    reading manifest file 'C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    Error in sitecustomize; set PYTHONVERBOSE for traceback:
    SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xcc in position 0: invalid continuation byte (sitecustomize.py, line 21)
    warning: no files found matching '*.py' under directory 'pymsgbox'
    writing manifest file 'C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.egg-info\SOURCES.txt'
    creating 'C:\Users\Миша\AppData\Local\Temp\pip-modern-metadata-f8srr00j\PyMsgBox.dist-info'
    error: invalid command 'bdist_wheel'
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'c:\python38\python.exe' 'c:\python38\lib\site-packages\pip\_vendor\pep517\_in_process.py' prepare_metadata_for_build_wheel 'C:\Users\CA81~1\AppData\Local\Temp\tmphpcf9lnw' Check the logs for full command output.

I haven't tried to do something yet because I don't understand the error. Any ideas?

Body:
I found the solution:

rollback pip to an older version:

python -m pip install pip==18.1

install desired module:

pip install pyautogui

update pip:

python -m pip install --upgrade pip

P.S. this solution works for other modules too.


问:
React onClick element: call another class elements
I am trying to achieve a modal popup(which is stored in postview class) to appear when a onclick is called in any post on postcontainer class. I am new to react, so I would love your suggestion on improving code.

Class 1 (PostCointainer)
This is main class which shows multiple post from an array. I want the modal to appear from class 2 when any post is clicked

```<code>import React, { Component, useState } from 'react';
import '../App.css';
import PostView from './PostView';
function RenderPost({posts}) {
    return (
     <div className="post-holder shadow-sm p-3 mb-4 bg-white rounded" key={posts.id} onClick={class postview class 2}>

    </div>
    );
}

const PostContainer = props => {

    const menu = props.posts.map(post => {
        return (
                <RenderPost posts={post} />
        )
    });

    return (
        <div className="container-fluid">
            <div className="row justify-content-center">
            <PostView />
               {menu}
            </div>
        </div>
    );
}

export default PostContainer;
</code>```

Class 2 (post View)

```<code>class PostView extends Component {

    constructor(props) {
        super(props);
        this.state = {
            isModalOpen : true,

        }
        this.toggleModal = this.toggleModal.bind(this);
    }

    toggleModal(e) {
        e.stopPropagation()
        this.setState({
          isModalOpen: !this.state.isModalOpen
        });
    }

    render() {
        return (
    <div className="shadow-sm p-2 mb-2 bg-white">
        <div
           className="modal"
           style={{display: this.state.isModalOpen ? 'block' : 'none' }}
           onClick={this.toggleModal} >
            <div
               className="modal-content"
               onClick={ e => e.stopPropagation() }  >
               <span
                   className="close"
                   onClick={this.toggleModal}
                >×
               </span>
            <div className="container">
                <h3 className="form-header">Hello</h3>

              </div>
            </div>
         </div>
    </div>
        );
    }
}
export default PostView;
</code>```

答:
This can be simply acheived by maintaining a state variabe for post click in the parent component and passing it via prop to child.

PostContainer.js

```<code>import React, { Component, useState } from 'react';
import '../App.css';
import PostView from './PostView';

const PostContainer = props => {
    const [post, setPost] = useState(false);

  function RenderPost({posts}) {
    return (
     <div className="post-holder shadow-sm p-3 mb-4 bg-white rounded" key={posts.id} onClick={setPost(posts)}>

    </div>
    );
  }

   const menu = props.posts.map(post => {
        return (
                <RenderPost posts={post} />
        )
    });

    return (
         <div className="container-fluid">
            <div className="row justify-content-center">
            <PostView post={post} />
               {menu}
            </div>
        </div>
     );
}

export default PostContainer;
</code>```

Constructor function of PostView Component

```<code>constructor(props) {
    super(props);
    this.state = {
        isModalOpen : !!props.post,
    }
    this.toggleModal = this.toggleModal.bind(this);
}
</code>```

And you can use the same post prop to render post in render function of your child component.
Hope it helps!!

Body:
I am trying to achieve a modal popup(which is stored in postview class) to appear when a onclick is called in any post on postcontainer class. I am new to react, so I would love your suggestion on improving code.

Class 1 (PostCointainer)
This is main class which shows multiple post from an array. I want the modal to appear from class 2 when any post is clicked

import React, { Component, useState } from 'react';
import '../App.css';
import PostView from './PostView';
function RenderPost({posts}) {
    return (

    );
}

const PostContainer = props => {

    const menu = props.posts.map(post => {
        return (
                <RenderPost posts={post} />
        )
    });

    return (

            <PostView />
               {menu}

    );
}

export default PostContainer;

Class 2 (post View)

class PostView extends Component {

    constructor(props) {
        super(props);
        this.state = {
            isModalOpen : true,

        }
        this.toggleModal = this.toggleModal.bind(this);
    }

    toggleModal(e) {
        e.stopPropagation()
        this.setState({
          isModalOpen: !this.state.isModalOpen
        });
    }

    render() {
        return (

 e.stopPropagation() }  >
               ×

Hello

        );
    }
}
export default PostView;

Body:
This can be simply acheived by maintaining a state variabe for post click in the parent component and passing it via prop to child.

PostContainer.js

import React, { Component, useState } from 'react';
import '../App.css';
import PostView from './PostView';

const PostContainer = props => {
    const [post, setPost] = useState(false);

  function RenderPost({posts}) {
    return (
     <div className="post-holder shadow-sm p-3 mb-4 bg-white rounded" key={posts.id} onClick={setPost(posts)}>

    </div>
    );
  }

   const menu = props.posts.map(post => {
        return (
                <RenderPost posts={post} />
        )
    });

    return (
         <div className="container-fluid">
            <div className="row justify-content-center">
            <PostView post={post} />
               {menu}
            </div>
        </div>
     );
}

export default PostContainer;

Constructor function of PostView Component

constructor(props) {
    super(props);
    this.state = {
        isModalOpen : !!props.post,
    }
    this.toggleModal = this.toggleModal.bind(this);
}

And you can use the same post prop to render post in render function of your child component.
Hope it helps!!


问:
State list of world with country-code
Where can I found the list of all the states of world with their country code (ISO2 or ISO3).

I have to insert all these states in my database. If the list is available in the .sql will be great.

I need state list of world with country-code not the country list.

Do you know where can I found?

Thanks in Advance.

答:
Wikipedia has the full list of both 2-letter and 3-letter country codes:

http://en.wikipedia.org/wiki/ISO_3166-1

With regards to having it in a local DB table, note that this list does occasionally change as nations are created, renamed or merged, so although it's not very frequent, you do need to keep it up-to-date, and also importantly, know what you're going to do with codes which become obsolete (ie if you've got cross-references to it from other tables, you can't just delete a record without making the cross-references invalid)

[EDIT]

You comment that you're looking for a state list.

This phrase "state list" is confusing. Are you using the word "state" as its used in the US. Other countries would refer to those as provinces, regions, counties, cantons, or a range of other terms.

More importantly, very few countries have codes for their individual regions.

For example, the UK is broken into counties such as Yorkshire, Hampshire and Surrey, but there aren't any codes that map to these names. There are short abbreviated versions of some of the names (ie 'Hants'=='Hampshire'), but they're colloquial abbreviations; certainly not official.  There are also UK postcodes which do provide codes for areas, but these do not map to named counties. And other countries don't even have that.

Title: State list of world with country-code


问:
ResourceNotFoundException for existing DynamoDB table
I've already read this question on the topic, but it doesn't help (see below).

I have a DDB Table my_table in eu-west-1, which I can (successfully) scan from my EC2 (same region, with AmazonDynamoDBFullAccess attached to its IAM) instance with AWS CLI:

```<code>aws dynamodb scan --table-name my_table --region eu-west-1
</code>```

This is the Java model that I've created:

```<code>@DynamoDBTable(tableName="my_table")
public class TableModel {
  @DynamoDBHashKey(attributeName = "partition_key")
  private final Long partitionKey;
  // ...
}
</code>```

And this is how I query it (code executed from same EC2):

```<code>public class DDBQuery {
    private DynamoDBMapper dynamoDBMapper;
    public DDBQuery() {
        dynamoDBMapper = new DynamoDBMapper(AmazonDynamoDBClientBuilder.standard()
                .withRegion(Regions.EU_WEST_1).build());
    }
    public void scan() {
        final List<DRTFacet> result = dynamoDBMapper.scan(TableModel.class, new DynamoDBScanExpression()); // Exception!
    }
}
</code>```

However, I get the title exception.
Note: vars have been renaming for sake of simplicity and confidentiality.

答:
I'm quite surprised to find out that the root error was because I the annotation in the actual class was of the type:

```<code>@DynamoDBTable(tableName=MyConstantsClass.TABLE_NAME)
</code>```

That damned MyConstantsClass. generated the error.

As soon as I refactored this into:

```<code>//Appropriate import for TABLE_NAME
@DynamoDBTable(tableName=TABLE_NAME)
</code>```

The error disappeared.

Body:
I've already read this question on the topic, but it doesn't help (see below).

I have a DDB Table my_table in eu-west-1, which I can (successfully) scan from my EC2 (same region, with AmazonDynamoDBFullAccess attached to its IAM) instance with AWS CLI:

aws dynamodb scan --table-name my_table --region eu-west-1

This is the Java model that I've created:

@DynamoDBTable(tableName="my_table")
public class TableModel {
  @DynamoDBHashKey(attributeName = "partition_key")
  private final Long partitionKey;
  // ...
}

And this is how I query it (code executed from same EC2):

public class DDBQuery {
    private DynamoDBMapper dynamoDBMapper;
    public DDBQuery() {
        dynamoDBMapper = new DynamoDBMapper(AmazonDynamoDBClientBuilder.standard()
                .withRegion(Regions.EU_WEST_1).build());
    }
    public void scan() {
        final List<DRTFacet> result = dynamoDBMapper.scan(TableModel.class, new DynamoDBScanExpression()); // Exception!
    }
}

However, I get the title exception.
Note: vars have been renaming for sake of simplicity and confidentiality.

Body:
I'm quite surprised to find out that the root error was because I the annotation in the actual class was of the type:

@DynamoDBTable(tableName=MyConstantsClass.TABLE_NAME)

That damned MyConstantsClass. generated the error.

As soon as I refactored this into:

//Appropriate import for TABLE_NAME
@DynamoDBTable(tableName=TABLE_NAME)

The error disappeared.


问:
Regular Expression for a Kibana Search
I am trying to create a regular expression search within Kibana. I am new to regex and new to kibana, but the solution to this issue should not be too complex.

Right now I am filtering through the "message" field of a query of searches for the specific text Max Memory Used. Currently the search is returning all messages with that text field. However, the "Max Memory Used" phrase is followed by a statistic for example Max Memory Used: 65 MB. The issue I am having is that I do not know how to create the regex search to return both the Max Memory Used, and the __ MB, as the number of MB used is different every time.

The current used filter reads "Max Memory Used" in the search field.

答:
Use

```<code>Max Memory Used: [0-9]+ MB
</code>```

See proof. [0-9]+ will match one or more digits.

Title: Regular Expression for a Kibana Search

Body:
Use

Max Memory Used: [0-9]+ MB

See proof. [0-9]+ will match one or more digits.


问:
Is there a single PHP API to post to multiple sharing sites (Twitter, Reddit, Linkedin, etc)?
Is there a single PHP API to post to multiple sharing sites (Twitter, Reddit, Linkedin, YouTube etc), or do I have to use multiple APIs? Or is there an online service that will do this via, say, a REST interface?</p>

答:
There is no single API for all services, so to speak, but there are multiple GitHub projects that do this!

Social Share URLs

Sharer.js

I personally contribute to both of these projects on GitHub!  Even though there is a "support" button there for contributions for Sharer.js, they go to the project owners -- and I'm only a contributor, not a project owner!

ContentLicense: CC BY-SA 2.5


问:
What should a Traversable instance look like for a Tree datatype with a nested Maybe value?
I have a Haskell exam in three days, so I thought I should practice a little and pulled up past exams, one of which features the following Tree datatype:

```<code>data Tree a = Leaf1 a | Leaf2 a a | Node (Tree a) (Maybe (Tree a)) deriving (Eq, Ord, Show)
</code>```

It didn't seem that challenging at first, but then I realized I have to write a Traversable instance for this Tree. Dealing with the leaves were easy enough:

```<code>instance Traversable Tree where
  traverse f (Leaf1 a)   = Leaf1 <$> f a
  traverse f (Leaf2 a b) = Leaf2 <$> f a <*> f b
</code>```

However, I started running into problems with the Node.

```<code>  traverse f (Node t Nothing)  = Node <$> traverse f t <*> Nothing
  traverse f (Node l (Just r)) = Node <$> traverse f l <*> Just (traverse f r)
</code>```

Naturally, these don't work, and I can't wrap my head around what should come after the second <*>. I tried using holes, but the messages given to me by ghci didn't help much (I get that the problem is with types, but I have no idea how I'm supposed to fix it).

Here's the error message I got when I tried to compile it:

```<code>* Couldn't match type `f' with `Maybe'
  `f' is a rigid type variable bound by
    the type signature for:
      traverse :: forall (f :: * -> *) a b.
                  Applicative f =>
                  (a -> f b) -> Tree a -> f (Tree b)
    at exam.hs:92:3-10
  Expected type: f (Maybe (Tree b))
    Actual type: Maybe (Maybe (Tree b))
* In the second argument of `(<*>)', namely `Nothing'
  In the expression: Node <$> traverse f t <*> Nothing
  In an equation for `traverse':
      traverse f (Node t Nothing) = Node <$> traverse f t <*> Nothing
* Relevant bindings include
    f :: a -> f b (bound at exam.hs:94:12)
    traverse :: (a -> f b) -> Tree a -> f (Tree b)
      (bound at exam.hs:92:3)
   |
94 |   traverse f (Node t Nothing)  = Node <$> traverse f t <*> Nothing
   |                                                            ^^^^^^^
</code>```

Could someone please give me some pointers or a possible fix for this issue?

答:
The short answer is that you need to use traverse to get inside the Maybe.

The Traversable and Foldable instances for a type often have a similar structure to its Functor instance. Whereas fmap maps a pure function over a structure, combining the results back up with the pure constructors:

```<code>instance Functor Tree where
  fmap f (Leaf1 a) = Leaf1 (f a)
  fmap f (Leaf2 a1 a2) = Leaf2 (f a1) (f a2)
  fmap f (Node ta mta) = Node (fmap f ta) (fmap (fmap f) mta)
</code>```

Note the (fmap (fmap f) mta): the outer fmap maps over the Maybe, while the inner one maps over the Tree:

```<code>(fmap
  :: (Tree a -> Tree b)
  -> Maybe (Tree a) -> Maybe (Tree b))
  ((fmap
    :: (a -> b)
    -> Tree a -> Tree b)
    f)
  mta
</code>```

traverse instead maps an effectful function over the structure, and correspondingly lifts the constructors into Applicative with the <$> and <*> operators:

```<code>instance Traversable Tree where
  traverse f (Leaf1 a) = Leaf1 <$> f a
  traverse f (Leaf2 a1 a2) = Leaf2 <$> f a1 <*> f a2
  traverse f (Node ta mta) = Node <$> traverse f ta <*> traverse (traverse f) mta
</code>```

Again, notice that we must traverse the Maybe, and within that, traverse the Tree, but instead of a pure function a -> b, we just have an effectful function a -> f b, given Applicative f:

```<code>(traverse
  :: (Tree a -> f (Tree b))
  -> Maybe (Tree a) -> f (Maybe (Tree b)))
  ((traverse
    :: (a -> f b)
    -> Tree a -> f (Tree b))
    f)
  mta
</code>```

Likewise, foldMap has a similar structure, but instead of reconstructing the data type, it combines results using a Monoid instance:

```<code>instance Foldable Tree where
  foldMap f (Leaf1 a) = f a
  foldMap f (Leaf2 a1 a2) = f a1 <> f a2
  foldMap f (Node ta mta) = foldMap f ta <> foldMap (foldMap f) mta
</code>```

And here’s a simple example usage of traverse:

```<code>> traverse (\ x -> print x *> pure (x + 1)) (Node (Leaf1 10) (Just (Leaf2 20 30)))
10
20
30
Node (Leaf1 11) (Just (Leaf2 21 31))
</code>```

With the DeriveFoldable, DeriveFunctor, and DeriveTraversable extensions, you may add a deriving (Foldable, Functor, Traversable) clause to a data type and use the -ddump-deriv flag of GHC to see the generated code.

Body:
I have a Haskell exam in three days, so I thought I should practice a little and pulled up past exams, one of which features the following Tree datatype:

data Tree a = Leaf1 a | Leaf2 a a | Node (Tree a) (Maybe (Tree a)) deriving (Eq, Ord, Show)

It didn't seem that challenging at first, but then I realized I have to write a Traversable instance for this Tree. Dealing with the leaves were easy enough:

instance Traversable Tree where
  traverse f (Leaf1 a)   = Leaf1 <$> f a
  traverse f (Leaf2 a b) = Leaf2 <$> f a <*> f b

However, I started running into problems with the Node.

  traverse f (Node t Nothing)  = Node <$> traverse f t <*> Nothing
  traverse f (Node l (Just r)) = Node <$> traverse f l <*> Just (traverse f r)

Naturally, these don't work, and I can't wrap my head around what should come after the second <*>. I tried using holes, but the messages given to me by ghci didn't help much (I get that the problem is with types, but I have no idea how I'm supposed to fix it).

Here's the error message I got when I tried to compile it:

* Couldn't match type `f' with `Maybe'
  `f' is a rigid type variable bound by
    the type signature for:
      traverse :: forall (f :: * -> *) a b.
                  Applicative f =>
                  (a -> f b) -> Tree a -> f (Tree b)
    at exam.hs:92:3-10
  Expected type: f (Maybe (Tree b))
    Actual type: Maybe (Maybe (Tree b))
* In the second argument of `(<*>)', namely `Nothing'
  In the expression: Node <$> traverse f t <*> Nothing
  In an equation for `traverse':
      traverse f (Node t Nothing) = Node <$> traverse f t <*> Nothing
* Relevant bindings include
    f :: a -> f b (bound at exam.hs:94:12)
    traverse :: (a -> f b) -> Tree a -> f (Tree b)
      (bound at exam.hs:92:3)
   |
94 |   traverse f (Node t Nothing)  = Node <$> traverse f t <*> Nothing
   |                                                            ^^^^^^^

Could someone please give me some pointers or a possible fix for this issue?

Body:
The short answer is that you need to use traverse to get inside the Maybe.

The Traversable and Foldable instances for a type often have a similar structure to its Functor instance. Whereas fmap maps a pure function over a structure, combining the results back up with the pure constructors:

instance Functor Tree where
  fmap f (Leaf1 a) = Leaf1 (f a)
  fmap f (Leaf2 a1 a2) = Leaf2 (f a1) (f a2)
  fmap f (Node ta mta) = Node (fmap f ta) (fmap (fmap f) mta)

Note the (fmap (fmap f) mta): the outer fmap maps over the Maybe, while the inner one maps over the Tree:

(fmap
  :: (Tree a -> Tree b)
  -> Maybe (Tree a) -> Maybe (Tree b))
  ((fmap
    :: (a -> b)
    -> Tree a -> Tree b)
    f)
  mta

traverse instead maps an effectful function over the structure, and correspondingly lifts the constructors into Applicative with the <$> and <*> operators:

instance Traversable Tree where
  traverse f (Leaf1 a) = Leaf1 <$> f a
  traverse f (Leaf2 a1 a2) = Leaf2 <$> f a1 <*> f a2
  traverse f (Node ta mta) = Node <$> traverse f ta <*> traverse (traverse f) mta

Again, notice that we must traverse the Maybe, and within that, traverse the Tree, but instead of a pure function a -> b, we just have an effectful function a -> f b, given Applicative f:

(traverse
  :: (Tree a -> f (Tree b))
  -> Maybe (Tree a) -> f (Maybe (Tree b)))
  ((traverse
    :: (a -> f b)
    -> Tree a -> f (Tree b))
    f)
  mta

Likewise, foldMap has a similar structure, but instead of reconstructing the data type, it combines results using a Monoid instance:

instance Foldable Tree where
  foldMap f (Leaf1 a) = f a
  foldMap f (Leaf2 a1 a2) = f a1 <> f a2
  foldMap f (Node ta mta) = foldMap f ta <> foldMap (foldMap f) mta

And here’s a simple example usage of traverse:

> traverse (\ x -> print x *> pure (x + 1)) (Node (Leaf1 10) (Just (Leaf2 20 30)))
10
20
30
Node (Leaf1 11) (Just (Leaf2 21 31))

With the DeriveFoldable, DeriveFunctor, and DeriveTraversable extensions, you may add a deriving (Foldable, Functor, Traversable) clause to a data type and use the -ddump-deriv flag of GHC to see the generated code.


问:
Setting value if two conditions are true
I have a table that contains three columns. I need to set a value in column C that depends on column A and B. If all the values in column B are the same for a fixed value in column A then each row in column C needs to say "Pass" otherwise "Fail".

In the example screenshot the status is "Pass" for all values with ID = 2 because all values in the column "Name" are the same e.g. C

Example Table

答:
A simple IF and COUNTIFS:

```<code>=IF(COUNTIFS(A:A,A2,B:B,"<>"&B2)=0,"Pass","Fail")
</code>```

Body:
A simple IF and COUNTIFS:

=IF(COUNTIFS(A:A,A2,B:B,"<>"&B2)=0,"Pass","Fail")


问:
Getting data between components in Vue JS
I really can't get binding data between components.

Steps,

get text value from Child1 component

execute Add method on App.vue

send test value from App.vue and make a v-for list on Child2

No.3 is not working.
I dont' even know 1,2 are correct on code..
How can I get input data to show item list?

Here's my code: Link

答:
Code fixed: https://codesandbox.io/s/parent-to-childbyclicking-pp4yy

You emit a input event on Child1, but the App.vue was not listening. Also, the list was wrongly pass on Child2 props.

Feel free to comment if you don't understand any part ;)


答:
Use, the combination of pd.merge, Series.fillna, Series.sort_values, Series.rename:

```<code>df = pd.merge(
    df1.rename(columns={'cx1': 'cx'}), df2.rename(columns={'cx2': 'cx'}),
    on=['cx', 'Date'], how='outer', suffixes=('_1', '_2'))

df = df.sort_values(by='cx').fillna(0)
df[['cx', 'Amount_1', 'Amount_2']] = df[['cx', 'Amount_1', 'Amount_2']].astype(int)
</code>```

Result:

```<code>   cx       Date  Amount_1  Amount_2
0   1  11/1/2019       400       300
1   1  12/1/2019       200         0
2   2  15/1/2019       400         0
4   2  16/1/2019         0       200
3   3  16/1/2019       500       400
</code>```

Title: Merge two tabel

Body:
I have two tables. I need to merge two tables with cx1, cx2 and Date keys. How is it?

fist table
cx1   Date       Amount
1     11/1/2019   400
1     12/1/2019   200
2     15/1/2019   400
3     16/1/2019   500

Second Table
cx2    Date        Amount
1      11/1/2019   300
2      16/1/2019   200
3      16/1/2019   400

Final output
cx     Date        Amount_1    Amount_2
1      11/1/2019   400         300
1      12/1/2019   0           300
2      15/1/2019   400         0
2      16/1/2019   0           200
3      16/1/2019   500         400

Body:
Use, the combination of pd.merge, Series.fillna, Series.sort_values, Series.rename:

df = pd.merge(
    df1.rename(columns={'cx1': 'cx'}), df2.rename(columns={'cx2': 'cx'}),
    on=['cx', 'Date'], how='outer', suffixes=('_1', '_2'))

df = df.sort_values(by='cx').fillna(0)
df[['cx', 'Amount_1', 'Amount_2']] = df[['cx', 'Amount_1', 'Amount_2']].astype(int)

Result:

   cx       Date  Amount_1  Amount_2
0   1  11/1/2019       400       300
1   1  12/1/2019       200         0
2   2  15/1/2019       400         0
4   2  16/1/2019         0       200
3   3  16/1/2019       500       400


问:
Can I trigger my Azure data factory pipeline in 5 working day between 9 am to 6 pm hourly
I have a Azure data factory pipeline that load data of every working day(Run every working day). I want to trigger my pipeline every working day (Mon-Fry) between working hour(9am to 6pm) and hourly.
It should run as daily at 9am then 10am then 11am--------at 6pm.
I have tried tumbling window trigger but I think it does not support time period for trigger interval</p>

答:
The recurrence patterns in ADF and Logic Apps don't directly support this combination of requirements. You are certainly welcome to attempt this in an ADF pipeline, but I find Logic Apps to be much easier for this sort of action. Below is an example of how you might configure it:

Create a Logic App with a Recurrence Trigger

In the Trigger, change the Frequency to Day and specify the hours and timezone:

Calculate the day of the week

Us the following expression (change to the appropriate timezone) to extract the day of the week into a variable:

```<code>dayOfWeek(convertFromUtc(utcNow(), 'Eastern Standard Time'))
</code>```

This will return an integer where 0 = Sunday, 1 = Monday, etc.

Add condition based on the day of the week

Use the dayOfWeek integer variable to determine which days to act (or ignore). In this example, I'm exceluding days 0 (Sunday) and 6 (Saturday):

Execute the data factory

In the True condition, execute your data factory (do nothing in the False condition):

Body:
The recurrence patterns in ADF and Logic Apps don't directly support this combination of requirements. You are certainly welcome to attempt this in an ADF pipeline, but I find Logic Apps to be much easier for this sort of action. Below is an example of how you might configure it:

Create a Logic App with a Recurrence Trigger

In the Trigger, change the Frequency to Day and specify the hours and timezone:

Calculate the day of the week

Us the following expression (change to the appropriate timezone) to extract the day of the week into a variable:

dayOfWeek(convertFromUtc(utcNow(), 'Eastern Standard Time'))

This will return an integer where 0 = Sunday, 1 = Monday, etc.

Add condition based on the day of the week

Use the dayOfWeek integer variable to determine which days to act (or ignore). In this example, I'm exceluding days 0 (Sunday) and 6 (Saturday):

Execute the data factory

In the True condition, execute your data factory (do nothing in the False condition):


问:
Why does removal of async/await cause conversion error for Task<T> to Task<object>
I have the following generic and non-generic methods:

public async Task<T> LoadAsync(Guid id)
{
    return await _someService.SomeMethodAsync(id);
}

async Task<object> LoadObjectAsync(Guid id) => await LoadAsync(id);
```

<p>Trying to follow the advice from Stephen Cleary, I thought I'd make the code more efficient by removing the async/await from the <code>LoadObjectAsync</code> method as it is a passthrough. However, when I change the signature to:</p>

<pre class="lang-cs prettyprint-override"><code>Task<object> LoadObjectAsync(Guid id) => LoadAsync(id);
</code>```

I get an error saying I cannot implicitly convert from Task<T> to Task<object>. What I'd like to know is how the async await avoids this conversion issue? I know that generic variance prohibits the conversion of the Task<> but why does this not apply to the async/await version?

答:
Trying to follow the advice from Stephen Cleary

The advice in that article is "leave the async/await in there unless you need to remove it". In this case, the method looks like a passthrough but is actually doing an implicit cast.

What I'd like to know is why the async await avoids this conversion issue?

With async and await, the code is casting T to object, which is always allowed.

Without async and await, the code is casting Task<T> to Task<object>, which is not allowed. This is because classes cannot support generic variance, and there is no ITask<T> type.

Body:
I have the following generic and non-generic methods:

public async Task<T> LoadAsync(Guid id)
{
    return await _someService.SomeMethodAsync(id);
}

async Task<object> LoadObjectAsync(Guid id) => await LoadAsync(id);

Trying to follow the advice from Stephen Cleary, I thought I'd make the code more efficient by removing the async/await from the LoadObjectAsync method as it is a passthrough. However, when I change the signature to:

Task<object> LoadObjectAsync(Guid id) => LoadAsync(id);

I get an error saying I cannot implicitly convert from Task<T> to Task<object>. What I'd like to know is how the async await avoids this conversion issue? I know that generic variance prohibits the conversion of the Task<> but why does this not apply to the async/await version?


问:
How can I group multiple columns in different ways finding new occurrences?
I have the following dataset in this format:

```<code>bill_id patient_id Date_of_purchase
14           321      23-4-17
29           123      25-4-17
29           123      25-4-17
29           123      25-4-17
35           321      28-6-18
35           321      28-6-18
</code>```

For the same bill_id, the row of purchase belongs to the same bill.

For the same patient_id, it corresponds to the same person.

Date is the date when the purchase was made.

What I want to do is to figure out the number of old and new customers who made a purchase from any start date to any given date. It counts as old if the person's patient id had already made a purchase before. Rest are new.

Is there any standard pandas function to group and compare multiple columns like this based on different conditions?

Something like the following function and output:

```<code>foo(start_date, end_date):

   return old customers, new customers.
## E.g. foo(19-4-17,30-6-19) is (1,1) as patient_id number 321 came twice and is hence counted as old.
</code>```

答:
This code snippet runs on its own and uses some groupby and merging magic:

```<code>import pandas as pd
from datetime import datetime

df = pd.DataFrame({"bill_id": [1, 1, 2, 3, 3],
                   "patient_id": [1, 2, 3, 4, 4],
                   "date": [datetime(2020, 1, 1),
                            datetime(2020, 1, 2),
                            datetime(2020, 1, 3),
                            datetime(2020, 1, 4),
                            datetime(2020, 1, 5)]
})

start_date = datetime(2020, 1, 2)
end_date = datetime(2020, 1, 5)

first_purchase = df.groupby(["patient_id"]).agg({"date": "min"})
first_purchase["first_purchase"] = 1
df = df.merge(first_purchase, how="left").fillna(0).astype({"first_purchase": "int"}).rename(columns={"first_purchase": "new_purchase"})
df["old_purchase"] = 1-df["new_purchase"]

idx = (df["date"]>=start_date)&(df["date"]<=end_date)
df.loc[idx, "new_purchase"].sum(), df.loc[idx, "old_purchase"].sum()
</code>```

Explanation

We first groupby patient_id and get the minimum dates (i.e. the date the patient first purchased). For those dates and patient_ids, we set the "new_purchase" columns to true. The "old_purchase" column is just the inverse. Finally, we select the subset of the data by date and sum over the respective columns.

Body:
I have the following dataset in this format:

bill_id patient_id Date_of_purchase
14           321      23-4-17
29           123      25-4-17
29           123      25-4-17
29           123      25-4-17
35           321      28-6-18
35           321      28-6-18

For the same bill_id, the row of purchase belongs to the same bill.

For the same patient_id, it corresponds to the same person.

Date is the date when the purchase was made.

What I want to do is to figure out the number of old and new customers who made a purchase from any start date to any given date. It counts as old if the person's patient id had already made a purchase before. Rest are new.

Is there any standard pandas function to group and compare multiple columns like this based on different conditions?

Something like the following function and output:

foo(start_date, end_date):

   return old customers, new customers.
## E.g. foo(19-4-17,30-6-19) is (1,1) as patient_id number 321 came twice and is hence counted as old.

Body:
This code snippet runs on its own and uses some groupby and merging magic:

import pandas as pd
from datetime import datetime

df = pd.DataFrame({"bill_id": [1, 1, 2, 3, 3],
                   "patient_id": [1, 2, 3, 4, 4],
                   "date": [datetime(2020, 1, 1),
                            datetime(2020, 1, 2),
                            datetime(2020, 1, 3),
                            datetime(2020, 1, 4),
                            datetime(2020, 1, 5)]
})

start_date = datetime(2020, 1, 2)
end_date = datetime(2020, 1, 5)

first_purchase = df.groupby(["patient_id"]).agg({"date": "min"})
first_purchase["first_purchase"] = 1
df = df.merge(first_purchase, how="left").fillna(0).astype({"first_purchase": "int"}).rename(columns={"first_purchase": "new_purchase"})
df["old_purchase"] = 1-df["new_purchase"]

idx = (df["date"]>=start_date)&(df["date"]<=end_date)
df.loc[idx, "new_purchase"].sum(), df.loc[idx, "old_purchase"].sum()

Explanation

We first groupby patient_id and get the minimum dates (i.e. the date the patient first purchased). For those dates and patient_ids, we set the "new_purchase" columns to true. The "old_purchase" column is just the inverse. Finally, we select the subset of the data by date and sum over the respective columns.


问:
Calculate distance between two rotated elements
Hi I want to calculate the perpendicular distance between two rotated elements, when rotation is 0 I use el1.getBoundingClientRect().x - el2.getBoundingClientRect().x and it gives me right distance, but for rotated elements, it does not work as it gives the perpendicular distance between the vertexes (the distance of bounding rectangles, how can I get x? thanks!

https://codesandbox.io/s/epic-thunder-mxqbc?file=/src/index.js

答:
If differences of vertex coordinates of two rectangles  before rotation were (dx, dy), then after rotattion by angle fi new differences are:

```<code> nx = dx * cos(fi) - dy * sin(fi)
 ny = dx * sin(fi) + dy * cos(fi)
</code>```

If we multiply the first equation by cos(fi) and the second one by sin(fi), then add them, we can find needed value

```<code>dx = nx * cos(fi) + ny * sin(fi)
</code>```

(assuming you know vertex difference in rotated state)

For example below: dx was 25, cos(fi)=4/5, sin(fi)=3/5

After rotation: nx = 5, ny = 35, we can find dx = 5*4/5 + 25*3/5 = 4+21 = 25

Body:
If differences of vertex coordinates of two rectangles  before rotation were (dx, dy), then after rotattion by angle fi new differences are:

 nx = dx * cos(fi) - dy * sin(fi)
 ny = dx * sin(fi) + dy * cos(fi)

If we multiply the first equation by cos(fi) and the second one by sin(fi), then add them, we can find needed value

dx = nx * cos(fi) + ny * sin(fi)

(assuming you know vertex difference in rotated state)

For example below: dx was 25, cos(fi)=4/5, sin(fi)=3/5

After rotation: nx = 5, ny = 35, we can find dx = 5*4/5 + 25*3/5 = 4+21 = 25


问:
How do I integrate Oracle container registry with Azure DevOps?
I am having trouble creating a connection between Azure DevOps and Oracle Container Registry.

Has anyone experience how I get the fields requested by azure devops in oracle cloud?

The requested fields are:

Docker registry

Docker id

Docker password

Docker Service Connection

答:
Here are the inputs to the requested fields

Docker Registry: < region-key>.ocir.io (See here for region key information):

Docker ID: < tenancy-namespace>/< username>

  Password:  < User generated Auth Token>

More details about logging into OCIR can be found here.


问:
How to disable
 tags without disable
 tags in wordpress
I want to remove only
 tags without remove
 tags in pages wordpress, i only found remove
 tags and keep
, every i use remove_filter still remove
 tags.

答:
You can use strip_tags php function which removes php and html tags from a string.

This is for displaying the content: the_content()

https://developer.wordpress.org/reference/functions/the_content/

And this to retrieve the post content: get_the_content()

https://developer.wordpress.org/reference/functions/get_the_content/

(1) First way doing this: Change the page template of your theme

So in your page template, you normally will find the function call the_content().

But we need to retrieve the post content, remove the paragraph tags, and then display the "cleaned" content.

For that we will not use the_content() but use get_the_content().

```<code><?php
    $my_content = get_the_content();
    $clean_content = strip_tags($my_content , '<p>');
    echo $clean_content;
?>
</code>```

We saved the post content in a variable (get_the_content is returning a string) and then used strip_tags to remove the tags. We just need to echo the "cleaned" content.

(2) Alternative way doing this: Change the output of the_content() function

If you want to use the_content() function or do not have the possibility to change the theme files, you can make use of the_content filter in wordpress.

```<code>function remove_tags_from_the_content( $content ) {
    return strip_tags( $content, '<p>' );
}
add_filter( 'the_content', 'remove_tags_from_content' );
</code>```

This way everytime your the_content() function is called, the filter will be applied so the function returns your cleaned version.

(3) Another way: Remove auto paragraphs in wordpress content

Wordpress adds paragraph tags to the content by default. You can disable this behaviour (remove the filter) by putting the follwing code in the functions.php file of your theme:

```<code>// Prevent wordpress from adding paragraph tags on pages
function disable_pages_wpautop( $content ) {
  if ( is_singular( 'page' ) ) {
    remove_filter( 'the_content', 'wpautop' );
  }
  return $content;
}
add_filter( 'the_content', 'disable_pages_wpautop', 0 );
</code>```

You can replace the if condition with the post type you like:

```<code>if ( is_singular( 'your-post-type' ) )
</code>```

If you want to remove the paragraphs in the content and excerpt in pages, posts and other post-types, you can get rid of the if-clause:

```<code>function disable_wpautop_all( $content ) {
  remove_filter( 'the_content', 'wpautop' );
  remove_filter( 'the_excerpt', 'wpautop' );
  return $content;
}
add_filter( 'the_content', 'disable_wpautop_all', 0 );
</code>```

Title: How to disable <p> tags without disable <br> tags in wordpress

Body:
You can use strip_tags php function which removes php and html tags from a string.

This is for displaying the content: the_content()

https://developer.wordpress.org/reference/functions/the_content/

And this to retrieve the post content: get_the_content()

https://developer.wordpress.org/reference/functions/get_the_content/

(1) First way doing this: Change the page template of your theme

So in your page template, you normally will find the function call the_content().

But we need to retrieve the post content, remove the paragraph tags, and then display the "cleaned" content.

For that we will not use the_content() but use get_the_content().

<?php
    $my_content = get_the_content();
    $clean_content = strip_tags($my_content , '<p>');
    echo $clean_content;
?>

We saved the post content in a variable (get_the_content is returning a string) and then used strip_tags to remove the tags. We just need to echo the "cleaned" content.

(2) Alternative way doing this: Change the output of the_content() function

If you want to use the_content() function or do not have the possibility to change the theme files, you can make use of the_content filter in wordpress.

function remove_tags_from_the_content( $content ) {
    return strip_tags( $content, '<p>' );
}
add_filter( 'the_content', 'remove_tags_from_content' );

This way everytime your the_content() function is called, the filter will be applied so the function returns your cleaned version.

(3) Another way: Remove auto paragraphs in wordpress content

Wordpress adds paragraph tags to the content by default. You can disable this behaviour (remove the filter) by putting the follwing code in the functions.php file of your theme:

// Prevent wordpress from adding paragraph tags on pages
function disable_pages_wpautop( $content ) {
  if ( is_singular( 'page' ) ) {
    remove_filter( 'the_content', 'wpautop' );
  }
  return $content;
}
add_filter( 'the_content', 'disable_pages_wpautop', 0 );

You can replace the if condition with the post type you like:

if ( is_singular( 'your-post-type' ) )

If you want to remove the paragraphs in the content and excerpt in pages, posts and other post-types, you can get rid of the if-clause:

function disable_wpautop_all( $content ) {
  remove_filter( 'the_content', 'wpautop' );
  remove_filter( 'the_excerpt', 'wpautop' );
  return $content;
}
add_filter( 'the_content', 'disable_wpautop_all', 0 );


问:
Docker requires sudo to run
When I try to run any docker command, for example docker ps, I'm getting this error:

Got permission denied while trying to connect to the Docker daemon
  socket at unix:///var/run/docker.sock: Get
  http://%2Fvar%2Frun%2Fdocker.sock/v1.40/containers/json: dial unix
  /var/run/docker.sock: connect: permission denied

So I manage to run it using sudo:

```<code>sudo docker ps
</code>```

But I want to be able to run that without sudo.

答:
In order to achieve the desired result you have to do the post-installation steps described in the documentation:

Create the docker group.

```<code>$ sudo groupadd docker
</code>```

Add your user to the docker group.

```<code>$ sudo usermod -aG docker $USER
</code>```

Log out and log back in so that your group membership is re-evaluated.

Title: Docker requires sudo to run

Body:
When I try to run any docker command, for example docker ps, I'm getting this error:

Got permission denied while trying to connect to the Docker daemon
  socket at unix:///var/run/docker.sock: Get
  http://%2Fvar%2Frun%2Fdocker.sock/v1.40/containers/json: dial unix
  /var/run/docker.sock: connect: permission denied

So I manage to run it using sudo:

sudo docker ps

But I want to be able to run that without sudo.

Body:
In order to achieve the desired result you have to do the post-installation steps described in the documentation:

Create the docker group.

$ sudo groupadd docker

Add your user to the docker group.

$ sudo usermod -aG docker $USER

Log out and log back in so that your group membership is re-evaluated.


问:
Convert a list of string into a comma separated string without duplications
I have a list of strings in Java. I would like to to insert it into a string with commas, something like:

```<code>Input: [option1,option2,option3,option1,option4]
Output: option1,option2,option3,option4
</code>```

I saw this topic and I really liked this one:

```<code>        StringBuilder result = new StringBuilder();
        String delimiter= "";
        for (String i : list) {
            result.append(delimiter).append(i);
            delimiter = ",";
        }
        return result.toString();
</code>```

But what would be the best way to add support for unique only items? How can I return a string without any duplicates? I could remove duplication from list first but it feels like there is a better solution here.

答:
You can stream() the list and collect only distinct values. Afterwards, you can just String.join(...) them to a comma separated String, like this:

```<code>public static void main(String[] args) {
    // example values
    List<String> list = new ArrayList<>();
    list.add("option1");
    list.add("option2");
    list.add("option3");
    list.add("option4");
    list.add("option1");
    list.add("option3");
    list.add("option5");

    // stream the list and collect only distinct values in a new list
    List<String> distinctOptions = list.stream()
                                        .distinct()
                                        .collect(Collectors.toList());
    // then create a comma separated String from that list
    String commaSeparatedUniqueStrings = String.join(",", distinctOptions);
    // and print it
    System.out.println(commaSeparatedUniqueStrings);
}
</code>```

The output is

option1,option2,option3,option4,option5
```

Body:
I have a list of strings in Java. I would like to to insert it into a string with commas, something like:

Input: [option1,option2,option3,option1,option4]
Output: option1,option2,option3,option4

I saw this topic and I really liked this one:

        StringBuilder result = new StringBuilder();
        String delimiter= "";
        for (String i : list) {
            result.append(delimiter).append(i);
            delimiter = ",";
        }
        return result.toString();

But what would be the best way to add support for unique only items? How can I return a string without any duplicates? I could remove duplication from list first but it feels like there is a better solution here.

Body:
You can stream() the list and collect only distinct values. Afterwards, you can just String.join(...) them to a comma separated String, like this:

public static void main(String[] args) {
    // example values
    List<String> list = new ArrayList<>();
    list.add("option1");
    list.add("option2");
    list.add("option3");
    list.add("option4");
    list.add("option1");
    list.add("option3");
    list.add("option5");

    // stream the list and collect only distinct values in a new list
    List<String> distinctOptions = list.stream()
                                        .distinct()
                                        .collect(Collectors.toList());
    // then create a comma separated String from that list
    String commaSeparatedUniqueStrings = String.join(",", distinctOptions);
    // and print it
    System.out.println(commaSeparatedUniqueStrings);
}

The output is

option1,option2,option3,option4,option5


问:
dynamically created a tag onclick function not triger in jquery
I have developed a web app using jquery mobile. I wanted to call a function by clicking on the anchor tag which I've created dynamically. but it's not triggering and says the function is not defined. any help will highly be appreciated.

here is my code

```<code>function itemSearch(para) {
    $.ajax({
        url: "http://localhost:4000/products/filter/"+para,
        contentType: 'application/json',
        dataType: 'json',
        type: 'GET',
        success: function(data) {

            let output='';
            for (var i = 0; i < data.length; i++) {
                let img="http://localhost:4000/"+data[i].ImgPath.replace("Product\\","");
                output +=`
                    <li>
                        <a onclick="itemClicked('${data[i]._id}')" href="#" >
                            <img src="${img}">
                            <h3>${data[i].Category}</h3>
                            <p>Price : ${data[i].Price}</p>
                        </a>
                    </li>
                    `
                $('#items').html(output).listview('refresh');
                $('#search').val("");
            }
        }
    });
}

function itemClicked(id) {
 alert(id);
}
</code>```

答:
Since the itemClicked function is declared inside the scope of another function, the  tag cannot access it.

This demonstrates the problem, the solution is to move itemClicked to the global scope.

window.onload = function () {
  function itemClicked () {
    alert('itemClicked');
  }
}();

function globalIemClicked () {
    alert('globalIemClicked');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Run itemClicked<br/>
Run globalitemClicked</code>```

Body:
I have developed a web app using jquery mobile. I wanted to call a function by clicking on the anchor tag which I've created dynamically. but it's not triggering and says the function is not defined. any help will highly be appreciated.

here is my code

function itemSearch(para) {
    $.ajax({
        url: "http://localhost:4000/products/filter/"+para,
        contentType: 'application/json',
        dataType: 'json',
        type: 'GET',
        success: function(data) {

            let output='';
            for (var i = 0; i < data.length; i++) {
                let img="http://localhost:4000/"+data[i].ImgPath.replace("Product\\","");
                output +=`

${data[i].Category}

Price : ${data[i].Price}

                    `
                $('#items').html(output).listview('refresh');
                $('#search').val("");
            }
        }
    });
}

function itemClicked(id) {
 alert(id);
}

Body:
Since the itemClicked function is declared inside the scope of another function, the <a> tag cannot access it.

This demonstrates the problem, the solution is to move itemClicked to the global scope.

window.onload = function () {
  function itemClicked () {
    alert('itemClicked');
  }
}();

function globalIemClicked () {
    alert('globalIemClicked');
}

<a onclick="itemClicked()" href="#">Run itemClicked</a><br/>
<a onclick="globalIemClicked()" href="#">Run globalitemClicked</a>