问:
Alllow one extra filed into serializer and return validated data with that field in Django Rest Framework
I know on this topic people asked a question before but my case is different and I have implemented almost all the solutions which I found but none of them are worked for me.

First I have defined three classes in models:

models.py

class User(AbstractBaseUser, PermissionsMixin):
    """ User Model """

    username = None
    email = models.EmailField(max_length=255, unique=True)
    name = models.CharField(max_length=255)
    agency = models.ForeignKey('agency.Agency', on_delete=models.CASCADE, null=True)
    weekly_email = models.NullBooleanField()
    is_create_new_password = models.NullBooleanField(default=True)
    is_active = models.BooleanField(default=True)
    last_login_time = models.DateTimeField(null=True)
    last_login_from = models.CharField(max_length=255, null=True)
    created_at = models.DateField(default=timezone.now)
    updated_at = models.DateField(default=timezone.now)
    created_by = models.IntegerField(null=True)
    updated_by = models.IntegerField(null=True)

    """ The `USERNAME_FIELD` property tells us which field we will use to log in.
    In this case, we want that to be the email field. """
    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["username"]

    """ Tells Django that the UserManager class defined above should manage
    objects of this type. """
    objects = UserManager()

class Role(models.Model):
    """ Role Model """

    name = models.CharField(max_length=255, unique=True)

class UserRole(models.Model):
    """ User Role Model """

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    role = models.ForeignKey(Role, on_delete=models.CASCADE)
```

<p>Then I have defined my serializer for user module:</p>

<p><code>serializers.py</code>  </p>

<pre class="lang-py prettyprint-override"><code>class RegistrationSerializer(serializers.ModelSerializer):
    """ Serializers registration requests and creates a new user. """

    user_id = serializers.IntegerField(required=False)
    email = serializers.EmailField(max_length=255)
    name = serializers.CharField(max_length=255)
    agency_id = serializers.IntegerField(source='agency.id', required=False)
    role = serializers.CharField(source='role.name')
    weekly_email = serializers.NullBooleanField()
    last_login_time = serializers.DateTimeField(required=False)
    last_login_from = serializers.CharField(max_length=255, required=False)

    class Meta:
        model = User
        fields = (
            'role', 'user_id', 'email', 'name', 'agency_id', 'weekly_email', 'last_login_time',
            'last_login_from'
        )
</code>```

And At the end, I have defined my view file for user creation:

views.py

class UserCreateAPIView(APIView):
    """ User create Api view class """

    #Allow any user (authenticated or not) to hit this endpoint.
    permission_classes = (IsAuthenticated,)
    serializer_class = RegistrationSerializer

    def post(self, request):
        """ create user using following logic. """

        request.data['user_id'] = request.user.id
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(user=request.user)

        return Response({'message': response['user']['created'], 'data': serializer.data},
            status=status.HTTP_201_CREATED)
```

<p>Now when I run it everything works fine like user is created, role is created as per my expectations. My view, serializer and models excuted but at the end on this line:</p>

<pre class="lang-py prettyprint-override"><code>return Response({'message': response['user']['created'], 'data': serializer.data},
            status=status.HTTP_201_CREATED)
</code>```

I am facing error like,

```<code>AttributeError: Got AttributeError when attempting to get a value for field `role` on serializer `RegistrationSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `User` instance.
Original exception text was: 'User' object has no attribute 'role'.
</code>```

答:
I think you need to use ModelSerializer

```<code>class RegistrationSerializer(serializers.Serializer):

to

class RegistrationSerializer(serializers.ModelSerializer):
</code>```

Body:
I know on this topic people asked a question before but my case is different and I have implemented almost all the solutions which I found but none of them are worked for me.

First I have defined three classes in models:

models.py

class User(AbstractBaseUser, PermissionsMixin):
    """ User Model """

    username = None
    email = models.EmailField(max_length=255, unique=True)
    name = models.CharField(max_length=255)
    agency = models.ForeignKey('agency.Agency', on_delete=models.CASCADE, null=True)
    weekly_email = models.NullBooleanField()
    is_create_new_password = models.NullBooleanField(default=True)
    is_active = models.BooleanField(default=True)
    last_login_time = models.DateTimeField(null=True)
    last_login_from = models.CharField(max_length=255, null=True)
    created_at = models.DateField(default=timezone.now)
    updated_at = models.DateField(default=timezone.now)
    created_by = models.IntegerField(null=True)
    updated_by = models.IntegerField(null=True)

    """ The `USERNAME_FIELD` property tells us which field we will use to log in.
    In this case, we want that to be the email field. """
    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["username"]

    """ Tells Django that the UserManager class defined above should manage
    objects of this type. """
    objects = UserManager()

class Role(models.Model):
    """ Role Model """

    name = models.CharField(max_length=255, unique=True)

class UserRole(models.Model):
    """ User Role Model """

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    role = models.ForeignKey(Role, on_delete=models.CASCADE)

Then I have defined my serializer for user module:

serializers.py

class RegistrationSerializer(serializers.ModelSerializer):
    """ Serializers registration requests and creates a new user. """

    user_id = serializers.IntegerField(required=False)
    email = serializers.EmailField(max_length=255)
    name = serializers.CharField(max_length=255)
    agency_id = serializers.IntegerField(source='agency.id', required=False)
    role = serializers.CharField(source='role.name')
    weekly_email = serializers.NullBooleanField()
    last_login_time = serializers.DateTimeField(required=False)
    last_login_from = serializers.CharField(max_length=255, required=False)

    class Meta:
        model = User
        fields = (
            'role', 'user_id', 'email', 'name', 'agency_id', 'weekly_email', 'last_login_time',
            'last_login_from'
        )

And At the end, I have defined my view file for user creation:

views.py

class UserCreateAPIView(APIView):
    """ User create Api view class """

    #Allow any user (authenticated or not) to hit this endpoint.
    permission_classes = (IsAuthenticated,)
    serializer_class = RegistrationSerializer

    def post(self, request):
        """ create user using following logic. """

        request.data['user_id'] = request.user.id
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(user=request.user)

        return Response({'message': response['user']['created'], 'data': serializer.data},
            status=status.HTTP_201_CREATED)

Now when I run it everything works fine like user is created, role is created as per my expectations. My view, serializer and models excuted but at the end on this line:

return Response({'message': response['user']['created'], 'data': serializer.data},
            status=status.HTTP_201_CREATED)

I am facing error like,

AttributeError: Got AttributeError when attempting to get a value for field `role` on serializer `RegistrationSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `User` instance.
Original exception text was: 'User' object has no attribute 'role'.

Body:
I think you need to use ModelSerializer

class RegistrationSerializer(serializers.Serializer):

to

class RegistrationSerializer(serializers.ModelSerializer):


来源: stackexchange

问:
Getting an error (CS0012) telling me to add a reference to DevEx.Component.v9.1 but I already have a reference to the same component, but v16.1
I'm converting a project from .NET 2.0 to 4.0 and DevExpress v9.1 to v16.1. Everything was going smoothly until I got an error saying that the type 'XtraGrid.Views.Grid.GridView' is defined in the older assembly.

I've already deleted and re-added the correct reference. There isn't anything weird going on in the .csproj file either; the reference there is correct.

The error happens here

ErrorHandler.Instance.SetError(regInfoGridView, row, "str", i, "str")
```

<p>This is the header for SetError (from metadata):</p>

<pre class="lang-cs prettyprint-override"><code>public void SetError(GridView grid, DataRow row, string columnName, int rowHandle, string errMessage);
</code>```

The code seems simple enough, so I'm not sure why it might be asking for an old version of 'GridView'.

答:
I strongly suggest you to use the DevExpress Project Converter tool installed with DevExpress .NET components to update your projects when upgrading to a new version.

The Project Converter replaces references to outdated DevExpress assemblies in your projects with references to the most recent libraries.

The following files are updated during the conversion process:

project files (.csproj and .vbproj);

resource files (.resx) for forms that were localized in the Visual Studio Form Designer;

web application files (Web.config, .aspx, .ascx, .asax and .master);

other files, including .cs, .vb, .xaml, .skin, .config, .config.xml, .licx, .svc, .refresh, .uitest, and .lsml.

Video Tutorial

ContentLicense: CC BY-SA 4.0

Body:
I'm converting a project from .NET 2.0 to 4.0 and DevExpress v9.1 to v16.1. Everything was going smoothly until I got an error saying that the type 'XtraGrid.Views.Grid.GridView' is defined in the older assembly.

I've already deleted and re-added the correct reference. There isn't anything weird going on in the .csproj file either; the reference there is correct.

The error happens here

ErrorHandler.Instance.SetError(regInfoGridView, row, "str", i, "str")

This is the header for SetError (from metadata):

public void SetError(GridView grid, DataRow row, string columnName, int rowHandle, string errMessage);

The code seems simple enough, so I'm not sure why it might be asking for an old version of 'GridView'.


问:
Azure Notification Hub and UWP app with code-signing certificate (desktop bridge)
I have a desktop bridge app (WPF) which package is signed with a code-signing certificate, how should I configure Azure Notification Hub to receive push notifications from this app?

Azure requires a Package SID and a Security Key that I haven't because the app is not distributed on the store.

答:
Azure requires a Package SID and a Security Key that I haven't because the app is not distributed on the store.

To make the Azure Notification Hub send notification notification successfully, the Package SID and a Security Key is necessary. You could get the Package SID and a Security Key even if your app is not published to the MS store.

Please see the Create an app in Windows Store tutorial. In the step 3, click the 'Live Service Site', it will navigate directly to the Application Registration Portal. Sign in to your Microsoft account and select your application name, then you will see the Package SID and a Security Key on the page.

After that, right-click the packaged app project, select Store, and then select Associate App with the Store. You need to associate your project with the app that you created in the Windows Dev Center.


问:
Can't create "a" element on clicking and subsequently classList.toggle() not working
I am making a to-do list application. You enter an item. It gets appended to the list. On clicking the item on the list, it gets crossed. Can't make the text clickable and thus can't add the classList.toggle() function to cross the item from the list.

I've tried to create an empty "li" element to which an "a" element is created inside it. (Note: all this happens when we add the item to the list). I thought, using the "a" element, I could hover over the text and thus make it clickable and connect it to the classList.toggle() function.

```<code><html>
<head>
   <style>
   .done
   {
       text-decoration:line-through;
   }
   </style>
</head>
<body>
<input type="text" id="user_input">
<ul></ul>

<script>

var input = document.getElemenyById("user_input");

function addingNewList()
{
    var li = document.createElement("li");
    var tag = document.createElement("a");
    tag.appendChild(document.createTextNode(input.value));

    li.appendChild(tag);
    ul.appendChild(li);

    tag.onclick=tag.classList.toggle("done");
}
function input_length()
{
    return input.value.length;
}
input.addEventListener("keypress",function(event)
{
    if(input_length() >0 && event.which == 13)
    {
        addingNewList();
    }
})
</script>
</body>
</html>
</code>```

The expected output should be that, if the user add: "Do Laundry" to the list, It gets added to the list. On clicking "Do Laundry", there should be line through it, i.e it should be crossed. Currently, the items are getting added, but are not getting crossed. No error message is showing up either.

答:
While adding new li inside ul you need to bind addEventListener in new element, then on element click you need to add done class in to that element.

Try this:

<input type="text" id="user_input">

```

Body:
I am making a to-do list application. You enter an item. It gets appended to the list. On clicking the item on the list, it gets crossed. Can't make the text clickable and thus can't add the classList.toggle() function to cross the item from the list.

I've tried to create an empty "li" element to which an "a" element is created inside it. (Note: all this happens when we add the item to the list). I thought, using the "a" element, I could hover over the text and thus make it clickable and connect it to the classList.toggle() function.

<input type="text" id="user_input">

The expected output should be that, if the user add: "Do Laundry" to the list, It gets added to the list. On clicking "Do Laundry", there should be line through it, i.e it should be crossed. Currently, the items are getting added, but are not getting crossed. No error message is showing up either.

Body:
While adding new li inside ul you need to bind addEventListener in new element, then on element click you need to add done class in to that element.

Try this:

<html>
<head>
   <style>
   .done {
       text-decoration:line-through;
   }
   </style>
</head>
<body>
<input type="text" id="user_input">
<ul id="list"></ul>

<script>
var input = document.getElementById("user_input");

function addingNewList() {
 var li = document.createElement("li");
 var tag = document.createElement("a");
 tag.appendChild(document.createTextNode(input.value));

 li.appendChild(tag);

 li.addEventListener("click", function (event) {
   event.target.classList.add('done');
 })

 var ul = document.getElementById("list");
 ul.appendChild(li);

 // tag.onclick=tag.classList.toggle("done");
}

function input_length() {
 return input.value.length;
}
input.addEventListener("keypress", function (event) {
 if (input_length() > 0 && event.which == 13) {
  addingNewList();
 }
})
</script>
</body>
</html>


问:
Select column name per row for max value in PySpark
I have a dataframe like this, shown only two columns however there are many columns in original dataframe

```<code>data = [(("ID1", 3, 5)), (("ID2", 4, 12)), (("ID3", 8, 3))]
df = spark.createDataFrame(data, ["ID", "colA", "colB"])
df.show()

+---+----+----+
| ID|colA|colB|
+---+----+----+
|ID1|   3|   5|
|ID2|   4|  12|
|ID3|   8|   3|
+---+----+----+
</code>```

I want to extract the name of the column per row, which has the max value. Hence the expected output is like this

```<code>+---+----+----+-------+
| ID|colA|colB|Max_col|
+---+----+----+-------+
|ID1|   3|   5|   colB|
|ID2|   4|  12|   colB|
|ID3|   8|   3|   colA|
+---+----+----+-------+
</code>```

In case of tie, where colA and colB have same value, choose the first column.

How can I achieve this in pyspark

答:
You can use UDF on each row for row wise computation and use struct to pass multiple columns to udf. Hope this helps.

```<code>from pyspark.sql import functions as F
from pyspark.sql.types import IntegerType
from operator import itemgetter

data = [(("ID1", 3, 5,78)), (("ID2", 4, 12,45)), (("ID3", 70, 3,67))]
df = spark.createDataFrame(data, ["ID", "colA", "colB","colC"])
df.show()

+---+----+----+----+
| ID|colA|colB|colC|
+---+----+----+----+
|ID1|   3|   5|  78|
|ID2|   4|  12|  45|
|ID3|  70|   3|  70|
+---+----+----+----+
cols = df.columns

# to get max of values in a row
maxcol = F.udf(lambda row: max(row), IntegerType())
maxDF = df.withColumn("maxval", maxcol(F.struct([df[x] for x in df.columns[1:]])))
maxDF.show()

+---+----+----+----+-------+
|ID |colA|colB|colC|Max_col|
+---+----+----+----+-------+
|ID1|3   |5   |78  |78     |
|ID2|4   |12  |45  |45     |
|ID3|70  |3   |67  |70     |
+---+----+----+----+-------+

# to get max of value & corresponding column name

schema=StructType([StructField('maxval',IntegerType()),StructField('maxval_colname',StringType())])

maxcol = F.udf(lambda row: max(row,key=itemgetter(0)), schema)
maxDF = df.withColumn('maxfield', maxcol(F.struct([F.struct(df[x],F.lit(x)) for x in df.columns[1:]]))).\
select(df.columns+['maxfield.maxval','maxfield.maxval_colname'])

+---+----+----+----+------+--------------+
| ID|colA|colB|colC|maxval|maxval_colname|
+---+----+----+----+------+--------------+
|ID1| 3  | 5  | 78 | 78   | colC         |
|ID2| 4  | 12 | 45 | 45   | colC         |
|ID3| 70 | 3  | 67 | 68   | colA         |
+---+----+----+----+------+--------------+
</code>```

Body:
I have a dataframe like this, shown only two columns however there are many columns in original dataframe

data = [(("ID1", 3, 5)), (("ID2", 4, 12)), (("ID3", 8, 3))]
df = spark.createDataFrame(data, ["ID", "colA", "colB"])
df.show()

+---+----+----+
| ID|colA|colB|
+---+----+----+
|ID1|   3|   5|
|ID2|   4|  12|
|ID3|   8|   3|
+---+----+----+

I want to extract the name of the column per row, which has the max value. Hence the expected output is like this

+---+----+----+-------+
| ID|colA|colB|Max_col|
+---+----+----+-------+
|ID1|   3|   5|   colB|
|ID2|   4|  12|   colB|
|ID3|   8|   3|   colA|
+---+----+----+-------+

In case of tie, where colA and colB have same value, choose the first column.

How can I achieve this in pyspark

Body:
You can use UDF on each row for row wise computation and use struct to pass multiple columns to udf. Hope this helps.

from pyspark.sql import functions as F
from pyspark.sql.types import IntegerType
from operator import itemgetter

data = [(("ID1", 3, 5,78)), (("ID2", 4, 12,45)), (("ID3", 70, 3,67))]
df = spark.createDataFrame(data, ["ID", "colA", "colB","colC"])
df.show()

+---+----+----+----+
| ID|colA|colB|colC|
+---+----+----+----+
|ID1|   3|   5|  78|
|ID2|   4|  12|  45|
|ID3|  70|   3|  70|
+---+----+----+----+
cols = df.columns

# to get max of values in a row
maxcol = F.udf(lambda row: max(row), IntegerType())
maxDF = df.withColumn("maxval", maxcol(F.struct([df[x] for x in df.columns[1:]])))
maxDF.show()

+---+----+----+----+-------+
|ID |colA|colB|colC|Max_col|
+---+----+----+----+-------+
|ID1|3   |5   |78  |78     |
|ID2|4   |12  |45  |45     |
|ID3|70  |3   |67  |70     |
+---+----+----+----+-------+

# to get max of value & corresponding column name

schema=StructType([StructField('maxval',IntegerType()),StructField('maxval_colname',StringType())])

maxcol = F.udf(lambda row: max(row,key=itemgetter(0)), schema)
maxDF = df.withColumn('maxfield', maxcol(F.struct([F.struct(df[x],F.lit(x)) for x in df.columns[1:]]))).\
select(df.columns+['maxfield.maxval','maxfield.maxval_colname'])

+---+----+----+----+------+--------------+
| ID|colA|colB|colC|maxval|maxval_colname|
+---+----+----+----+------+--------------+
|ID1| 3  | 5  | 78 | 78   | colC         |
|ID2| 4  | 12 | 45 | 45   | colC         |
|ID3| 70 | 3  | 67 | 68   | colA         |
+---+----+----+----+------+--------------+


问:
Publish NodeJS Server Online
I'm currently having an issue when trying to port forward my modem to my Node.js server. Sorry if this is a duplicate question, i've spent some time looking at familiar topics.

I'm using the express framework, I've included a small snippet, so you can see what port the node.js server is listening too.

(Quick Question: Do I use server.listen or app.listen in this situation? What's the difference?)

```<code>var express = require('express');
var app = express();
var server = require('http').Server(app);

app.listen(4000);
</code>```

I've also attatched a picture containing:

The node.js server running.

ipconfig (so you can see my local IP address)

and a screenshot of my modems' port forward settings.

When I google "Whats my IP Address" and retrieve my public IP address, then navigate to it I receive an error on my browser stating that the server took to long to respond. I assume the server isn't being port forwarded, however I can't seem to isolate the issue.

Any help would be greatly appreciated?

答:
Your modem/wifi router's public IP address keeps changing frequently every now and then or when your router reboots.  This is because of DHCP.

Port forwarding and hacking your wifi router firewall rules to allow public access to your home or office network is an unsafe practice.

That's where simple tools like SocketXP come in handy.  SocketXP will provide you a public URL to access your NodeJS server running in your localhost machine like your home/office laptop or server.

Here is a great blog article on how to install and setup SocketXP to access your local NodeJS server from the internet.

Title: Publish NodeJS Server Online

Body:
I'm currently having an issue when trying to port forward my modem to my Node.js server. Sorry if this is a duplicate question, i've spent some time looking at familiar topics.

I'm using the express framework, I've included a small snippet, so you can see what port the node.js server is listening too.

(Quick Question: Do I use server.listen or app.listen in this situation? What's the difference?)

var express = require('express');
var app = express();
var server = require('http').Server(app);

app.listen(4000);

I've also attatched a picture containing:

The node.js server running.

ipconfig (so you can see my local IP address)

and a screenshot of my modems' port forward settings.

When I google "Whats my IP Address" and retrieve my public IP address, then navigate to it I receive an error on my browser stating that the server took to long to respond. I assume the server isn't being port forwarded, however I can't seem to isolate the issue.

Any help would be greatly appreciated?


问:
How to pass data from BottomSheetFragmentDialog?
the question is how to pass data from BottomSheetDialogFragment to Fragment or Activity and what would be the correct way ?

Here is my Fragment dialog that will be opened in my Frament and should save data from textview that is getting clicked on.

```<code>class BallTypeDialogFragment : BottomSheetDialogFragment() {

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) =
    inflater.inflate(R.layout.fragment_blood_type_dialog, container, false)

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    text_view_ball_O.setOnClickListener {
        text_view_ball_O.text
        Toast.makeText(context, "O+", Toast.LENGTH_SHORT).show()
    }
    text_view_ball_A.setOnClickListener {
        text_view_ball_A.text
        Toast.makeText(context, "A+", Toast.LENGTH_SHORT).show()
    }
    text_view_ball_AA.setOnClickListener {
        Toast.makeText(context, "AA+", Toast.LENGTH_SHORT).show()
    }
    text_view_blood_grop_minus.setOnClickListener {
        text_view_blood_grop_minus.text
        Toast.makeText(context, "-", Toast.LENGTH_SHORT).show()
    }
    text_view_ball_AAR.setOnClickListener {
        text_view_ball_AAR.text
        Toast.makeText(context, "R -", Toast.LENGTH_SHORT).show()
    }
    text_view_ball_AARS.setOnClickListener {
        text_view_ball_AARS.text
        Toast.makeText(context, "AARS -", Toast.LENGTH_SHORT).show()
    }
    text_view_ball_OO.setOnClickListener {
        text_view_ball_OO.text
        Toast.makeText(context, "OO -", Toast.LENGTH_SHORT).show()
    }
}
}
</code>```

And i Simply open it in my Fragment like this,even though I understand it is incorrect.

```<code> private fun showDialog() {
    val dialog = BallTypeDialogFragment()

    dialog.show(childFragmentManager, "BallTypeDialogFragment")
}
</code>```

答:
1- Create an interface.

```<code>interface DialogActivityContract{
  fun onPassDataRequsted(dataType: DataType)
}
</code>```

2- Implement that interface to the activity:

```<code>class ActivityThatHoldsTheDialogActivity : SomeAppCompactActivity(),DialogActivityContract{

//other methods here

override public void onPassDataRequsted(DataType dataType){
//handle data here
    }
}
</code>```

And in your fragment:

```<code>lateinit var dialogActivityContract: DialogActivityContract

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    dialogActivityContract = (activity as ActivityThatHoldsTheDialogActivity)

}

// some methods here

fun whenYouNeedToSendThatData(){
 dialogActivityContract.onPassDataRequsted(yourData)
}
</code>```

Another way of doing it is using the EventBus library.

Body:
the question is how to pass data from BottomSheetDialogFragment to Fragment or Activity and what would be the correct way ?

Here is my Fragment dialog that will be opened in my Frament and should save data from textview that is getting clicked on.

class BallTypeDialogFragment : BottomSheetDialogFragment() {

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) =
    inflater.inflate(R.layout.fragment_blood_type_dialog, container, false)

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    text_view_ball_O.setOnClickListener {
        text_view_ball_O.text
        Toast.makeText(context, "O+", Toast.LENGTH_SHORT).show()
    }
    text_view_ball_A.setOnClickListener {
        text_view_ball_A.text
        Toast.makeText(context, "A+", Toast.LENGTH_SHORT).show()
    }
    text_view_ball_AA.setOnClickListener {
        Toast.makeText(context, "AA+", Toast.LENGTH_SHORT).show()
    }
    text_view_blood_grop_minus.setOnClickListener {
        text_view_blood_grop_minus.text
        Toast.makeText(context, "-", Toast.LENGTH_SHORT).show()
    }
    text_view_ball_AAR.setOnClickListener {
        text_view_ball_AAR.text
        Toast.makeText(context, "R -", Toast.LENGTH_SHORT).show()
    }
    text_view_ball_AARS.setOnClickListener {
        text_view_ball_AARS.text
        Toast.makeText(context, "AARS -", Toast.LENGTH_SHORT).show()
    }
    text_view_ball_OO.setOnClickListener {
        text_view_ball_OO.text
        Toast.makeText(context, "OO -", Toast.LENGTH_SHORT).show()
    }
}
}

And i Simply open it in my Fragment like this,even though I understand it is incorrect.

 private fun showDialog() {
    val dialog = BallTypeDialogFragment()

    dialog.show(childFragmentManager, "BallTypeDialogFragment")
}

Body:
1- Create an interface.

interface DialogActivityContract{
  fun onPassDataRequsted(dataType: DataType)
}

2- Implement that interface to the activity:

class ActivityThatHoldsTheDialogActivity : SomeAppCompactActivity(),DialogActivityContract{

//other methods here

override public void onPassDataRequsted(DataType dataType){
//handle data here
    }
}

And in your fragment:

lateinit var dialogActivityContract: DialogActivityContract

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    dialogActivityContract = (activity as ActivityThatHoldsTheDialogActivity)

}

// some methods here

fun whenYouNeedToSendThatData(){
 dialogActivityContract.onPassDataRequsted(yourData)
}

Another way of doing it is using the EventBus library.


问:
how to filter all string sequence in array using javascript
I have a large array, and I want to filter it based on a string I pass it. This string could be one or two characters, up to an entire string.

Here's an example array:

```<code>var data = ["bourbon", "beer", "electric"]
</code>```

If I pass e, I want the result ["electric", "beer"].

How can I achieve this functionality?

答:
Use filter with includes:

var data = ["bourbon", "beer", "electric"];
const selectByLetter = l => data.filter(s => s.includes(l));
console.log(selectByLetter("e"));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: auto; }</code>```

ES5 syntax:

var data = ["bourbon", "beer", "electric"];
var selectByLetter = function(l) {
  return data.filter(function(s) {
    return s.indexOf(l) > -1;
  });
}
console.log(selectByLetter("e"));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: auto; }</code>```

Body:
I have a large array, and I want to filter it based on a string I pass it. This string could be one or two characters, up to an entire string.

Here's an example array:

var data = ["bourbon", "beer", "electric"]

If I pass e, I want the result ["electric", "beer"].

How can I achieve this functionality?

Body:
Use filter with includes:

var data = ["bourbon", "beer", "electric"];
const selectByLetter = l => data.filter(s => s.includes(l));
console.log(selectByLetter("e"));

.as-console-wrapper { max-height: 100% !important; top: auto; }

ES5 syntax:

var data = ["bourbon", "beer", "electric"];
var selectByLetter = function(l) {
  return data.filter(function(s) {
    return s.indexOf(l) > -1;
  });
}
console.log(selectByLetter("e"));

.as-console-wrapper { max-height: 100% !important; top: auto; }


问:
Set user-interaction to false of a native Google Sign In Button
Is there a parameter userIntetaction in GIDSignInButton class? I want the button to become non-responsive after it is pressed once.

```<code>@IBOutlet weak var signInButton: GIDSignInButton!
</code>```

I want to do something like -

```<code>signInButton.setUserInteraction = false
</code>```

答:
for disabling user interaction of any type of view in iOS, you can use this method:

```<code>view.userInteractionEnabled = false
</code>```

this thing you can apply to GIDSignInButton too.

Body:
Is there a parameter userIntetaction in GIDSignInButton class? I want the button to become non-responsive after it is pressed once.

@IBOutlet weak var signInButton: GIDSignInButton!

I want to do something like -

signInButton.setUserInteraction = false

Body:
for disabling user interaction of any type of view in iOS, you can use this method:

view.userInteractionEnabled = false

this thing you can apply to GIDSignInButton too.


问:
How to concatenate strings at assembly time (using CATSTR?)
I have multiple build configurations of a project, and they each need to have some globally defined strings. These strings should really be built at assembly time by concatenating a root and a config-specific suffix, for example, I might have the root "TABLE" and config A would use the suffix "ALPHA" and config "B" would use the suffix "BETA", so when I build A, I end up with my globally defined string having the value "TABLEALPHA" and for B, the value "TABLEBETA"

Ideally, the suffix is provided via the command line, via a /D type definition.

A complication is that we use a proprietary source language that first "compiles" to MASM then uses MASM to assemble. Which makes it hard to provide good sample code for what I've tried.

If someone could provide a snippet of MASM source showing the definition of the root literal string, a string literal suffix, and how to use CATSTR (or @CatStr???) to define a new global symbol that contains the concatenation of the two strings, I would hope (fingers crossed!) to be able to take it from there.

答:
Here's a complete working example that combines the string constant "TABLE" with a compile-time defined string named SUFFIXB and shows the result in a messagebox.

```<code>; ml /c /coff /DSUFFIXB=BETA test.asm
; link /SUBSYSTEM:WINDOWS test.obj

.586p
.model flat, stdcall
option casemap:none

include \masm32\include\windows.inc
include \masm32\include\kernel32.inc
include \masm32\include\user32.inc

includelib \masm32\lib\kernel32.lib
includelib \masm32\lib\user32.lib

ROOT textequ <TABLE>
msg CATSTR <">, ROOT, SUFFIXB, <">

.data
dlgmsg db msg,0
dlgtitle db "Title",0

.code
start:
invoke MessageBoxA, NULL, ADDR dlgmsg, ADDR dlgtitle, MB_OK
invoke ExitProcess, NULL

end start
</code>```

As a side note, masm's /EP option can be useful when trying to figure out preprocessor syntax, as it allows you to see what your code looks like after it has gone through the preprocessor.

Body:
Here's a complete working example that combines the string constant "TABLE" with a compile-time defined string named SUFFIXB and shows the result in a messagebox.

; ml /c /coff /DSUFFIXB=BETA test.asm
; link /SUBSYSTEM:WINDOWS test.obj

.586p
.model flat, stdcall
option casemap:none

include \masm32\include\windows.inc
include \masm32\include\kernel32.inc
include \masm32\include\user32.inc

includelib \masm32\lib\kernel32.lib
includelib \masm32\lib\user32.lib

ROOT textequ <TABLE>
msg CATSTR <">, ROOT, SUFFIXB, <">

.data
dlgmsg db msg,0
dlgtitle db "Title",0

.code
start:
invoke MessageBoxA, NULL, ADDR dlgmsg, ADDR dlgtitle, MB_OK
invoke ExitProcess, NULL

end start

As a side note, masm's /EP option can be useful when trying to figure out preprocessor syntax, as it allows you to see what your code looks like after it has gone through the preprocessor.


问:
Subset a dataframe based on quantiles
If I have this data frame:

```<code>df <- data.frame(time = seq(as.Date('2000-01-01'), length.out = 200, by = 'days'),
             a = rnorm(200,8.4, 22), b=rnorm(200,8.4, 22), d= rnorm(200,8.4, 22),
e=rnorm(200,8.4, 22))
</code>```

What would be the easiest way to subset this df so that the values from each columns should be higher than 10th% percentile but lower than 90th% one?

I could do this using a loop, i.e:

```<code>for (i in names(df[,2:5])){
  print(i)
  column <- df[,c('time', i)]
  q <- unname(quantile(column[,2], probs = c(0.1, 0.9))) # just for one column
  column <- column[column[,2] > q[1] &column[,2] < q[2],]
  df <- merge(df, column, by = 'time', all.x = T)
}
</code>```

But there are more simple and more elegant ways to do that using functions or packages like dplyr. Thanks!

答:
Here is a dplyr approach:

```<code>library(dplyr)

df %>%
  mutate_at(vars(a:e), function(x) if_else(between(percent_rank(x), .1, .9), x, NA_real_))
</code>```

Title: Subset a dataframe based on quantiles

Body:
If I have this data frame:

df <- data.frame(time = seq(as.Date('2000-01-01'), length.out = 200, by = 'days'),
             a = rnorm(200,8.4, 22), b=rnorm(200,8.4, 22), d= rnorm(200,8.4, 22),
e=rnorm(200,8.4, 22))

What would be the easiest way to subset this df so that the values from each columns should be higher than 10th% percentile but lower than 90th% one?

I could do this using a loop, i.e:

for (i in names(df[,2:5])){
  print(i)
  column <- df[,c('time', i)]
  q <- unname(quantile(column[,2], probs = c(0.1, 0.9))) # just for one column
  column <- column[column[,2] > q[1] &column[,2] < q[2],]
  df <- merge(df, column, by = 'time', all.x = T)
}

But there are more simple and more elegant ways to do that using functions or packages like dplyr. Thanks!

Body:
Here is a dplyr approach:

library(dplyr)

df %>%
  mutate_at(vars(a:e), function(x) if_else(between(percent_rank(x), .1, .9), x, NA_real_))


问:
Spring Data - How to reuse repository in repository fragment?
Update: the following is using Spring Boot 2.1.0

I have a Spring Data repository and I am trying to provide some custom functionality to it, following the fragments example from the documentation.

So I've added an extra interface to the repository:

```<code>public interface UserRepository extends JpaRepository<User, Long>, UserExtraLogic {
    User findByFirstNameAndLastName(String firstName, String lastName);
}
</code>```

with this custom interface:

```<code>interface UserExtraLogic {
    void ensureHasAccess();
}
</code>```

and its implementation:

```<code>class UserExtraLogicImpl implements UserExtraLogic {
    public void ensureHasAccess() {
    }
}
</code>```

The problem is that I would like to be able to use my repositories inside UserExtraLogicImpl, so that I can reuse query methods like findByFirstNameAndLastName without having to write them by myself with EntityManager. So I tried this:

```<code>class UserExrtaLogicImpl implements UserExtraLogic {
    @Autowired
    private UserRepository userRepository;
}
</code>```

But then the application does not start. I get a NullPointerException, but I think it's just Spring getting into a cycle trying to resolve these dependencies.

Is what I'm trying to do possible? Is there another way to do this?

答:
I have the exactly the same code patterns and encounter the same problem in a recent project and I finally solve it by using @Lazy to lazy initialise UserRepository :

```<code>class UserExrtaLogicImpl implements UserExtraLogic {

    @Lazy
    @Autowired
    private UserRepository userRepository;

}
</code>```

Body:
Update: the following is using Spring Boot 2.1.0

I have a Spring Data repository and I am trying to provide some custom functionality to it, following the fragments example from the documentation.

So I've added an extra interface to the repository:

public interface UserRepository extends JpaRepository<User, Long>, UserExtraLogic {
    User findByFirstNameAndLastName(String firstName, String lastName);
}

with this custom interface:

interface UserExtraLogic {
    void ensureHasAccess();
}

and its implementation:

class UserExtraLogicImpl implements UserExtraLogic {
    public void ensureHasAccess() {
    }
}

The problem is that I would like to be able to use my repositories inside UserExtraLogicImpl, so that I can reuse query methods like findByFirstNameAndLastName without having to write them by myself with EntityManager. So I tried this:

class UserExrtaLogicImpl implements UserExtraLogic {
    @Autowired
    private UserRepository userRepository;
}

But then the application does not start. I get a NullPointerException, but I think it's just Spring getting into a cycle trying to resolve these dependencies.

Is what I'm trying to do possible? Is there another way to do this?

Body:
I have the exactly the same code patterns and encounter the same problem in a recent project and I finally solve it by using @Lazy to lazy initialise UserRepository :

class UserExrtaLogicImpl implements UserExtraLogic {

    @Lazy
    @Autowired
    private UserRepository userRepository;

}


问:
How to make php IF statement between Javascript variable and php value on page load without submitting form
I have to get Browser Local date and time with Javascript and compare it in PHP IF statement with value from database on page load to determine if product expired or not. How do I solve the issue without using cookies and or sessions?

Javascript

```<code> <script>

      var currentDate = new Date(),
      day = ('0' + (currentDate.getDate()+1)).slice(-2),
      month = ('0' + (currentDate.getMonth()+1)).slice(-2),
      year = currentDate.getFullYear();
      var currentTime = new Date(),
      hours = currentTime.getHours(),
      minutes = currentTime.getMinutes();

    if (minutes < 10) {
     minutes = '0' + minutes;
  }

 document.write(day + '/' + month + '/' + year + ' ' + hours + ':' + minutes)

</script>
</code>```

PHP

```<code>    if(strtotime( date and time from SCRIPT ) < strtotime($events date and time exiptation as $events_total_SKU[$e]['sales_end']))
{
   print(" OK ");
 .... and  shopping cart code
}
     else{
   print(" Expired ");
}
</code>```

答:
You should store both the dates in JavaScript variables as below. And compare it in Js as well.

```<code>  var currentDate = new Date(),
  day = ('0' + (currentDate.getDate()+1)).slice(-2),
  month = ('0' + (currentDate.getMonth()+1)).slice(-2),
  year = currentDate.getFullYear();
  var currentTime = new Date(),
  hours = currentTime.getHours(),
  minutes = currentTime.getMinutes();

  var frontendDate = year + '-' + month + '-' +day + ' ' + hours + ':' + minutes;

  var backednDateString = "<?php echo $events_total_SKU[$e]['sales_end'];?>";
  // As backedn date is string convert it as date first.
  var backednDateS  = new Date(backednDateString );

if(frontendDate  < backednDate)
{
   alert(" OK ");
}
else{
   alert(" Expired ");
}
</code>```

Make sure format of both the dates are same.

Body:
I have to get Browser Local date and time with Javascript and compare it in PHP IF statement with value from database on page load to determine if product expired or not. How do I solve the issue without using cookies and or sessions?

Javascript

PHP

    if(strtotime( date and time from SCRIPT ) < strtotime($events date and time exiptation as $events_total_SKU[$e]['sales_end']))
{
   print(" OK ");
 .... and  shopping cart code
}
     else{
   print(" Expired ");
}

Body:
You should store both the dates in JavaScript variables as below. And compare it in Js as well.

  var currentDate = new Date(),
  day = ('0' + (currentDate.getDate()+1)).slice(-2),
  month = ('0' + (currentDate.getMonth()+1)).slice(-2),
  year = currentDate.getFullYear();
  var currentTime = new Date(),
  hours = currentTime.getHours(),
  minutes = currentTime.getMinutes();

  var frontendDate = year + '-' + month + '-' +day + ' ' + hours + ':' + minutes;

  var backednDateString = "<?php echo $events_total_SKU[$e]['sales_end'];?>";
  // As backedn date is string convert it as date first.
  var backednDateS  = new Date(backednDateString );

if(frontendDate  < backednDate)
{
   alert(" OK ");
}
else{
   alert(" Expired ");
}

Make sure format of both the dates are same.


问:
How to get the coordinate x of a progress bar in javascript
I am trying to set the width of a progress bar using javascript, but I could not get the right width of the progress bar. </p>

```<code><div id="defaultBar">
  <div id="progressbar"></div>
</div>

var bar = document.getElementById("defaultBar");
var progressBar = document.getElementById("progressbar");
    bar.addEventListener("click", clickBar, false);

function clickBar(event){
    var x = event.pageX - bar.offsetLeft;
    var time = x * audio.duration/barSize;
    audio.currentTime = time;
    progressBar.style.width = x + 'px';
}
</code>```

答:
Try:

```<code> var x = event.offsetX
</code>```

to get the X cordinate of the mouse pointer between that event and the padding edge of the target node.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to set the width of a progress bar using javascript, but I could not get the right width of the progress bar.

var bar = document.getElementById("defaultBar");
var progressBar = document.getElementById("progressbar");
    bar.addEventListener("click", clickBar, false);

function clickBar(event){
    var x = event.pageX - bar.offsetLeft;
    var time = x * audio.duration/barSize;
    audio.currentTime = time;
    progressBar.style.width = x + 'px';
}

Body:
Try:

 var x = event.offsetX

to get the X cordinate of the mouse pointer between that event and the padding edge of the target node.


问:
Having multiple separate arrays of data, is there any other more efficient method to merge them into objects?
I am trying to populate Json downloaded and populate them into an array of objects.  However, there are some complexity on how the data is structured, how would I be able to populate those arrays into objects efficiently?

The following is the basic structure of the Json Data downloaded from a web service:

```<code>{
    timestamp: [Date],
    openingStockPrice: [Double],
    closingStockPrice: [Double]
}
</code>```

E.g.

```<code>{
    timestamp: [2019-01-01, 2019-01-02, 2019-01-03....],
    openingStockPrice: [100.0, 101.0, 95.0, ...],
    closingStockPrice: [101.0, 95.0, 99.5, ...]
}
</code>```

Based on the data structure, there are three separate arrays with data types of dates and double.

Therefore, the first item of each of the arrays belongs to the stock pricing for that particular date.  The second item of each of the arrays belongs to the second day... etc.

Currently, I manage to loop through each of the array and populate the data into objects based on the following structure.

```<code>Struct StockPrice {
    timestamp: Date,
    openingStockPrice: Double,
    closingStockPrice: Double
}

var stockPrice: [StockPrice]
</code>```

I manage to organise the data into array of StockPrice objects by looping through each of the arrays separately.  However, looping through each array does not seem efficient at all as the data set becomes large.

Would any one know, possibly, another way to populate multiple arrays into one array of StockPrice objects (in this scenario)?

答:
Whatever you do, you would still have to iterate through your multiple arrays because you have to fetch each item. I doubt you can find a O(logN) solution because of the nature of the problem. The best is a O(n)

O(n) solution:

```<code>

var stockPrices = [StockPrice]()

//assuming timeStamps, openingStockPrices, closingStockPrices have the same number of elements
for i in 0 ..< timeStamps.count {
    let timeStamp = timeStamps[i]
    let openingStockPrice = openingStockPrice[i]
    let closingStockPrice = closingStockPrice[i]
    let stockPrice = StockPrice(timeStamp, openingStockPrice, closingStockPrice)
    stockPrices(add: stockPrice)
}

</code>```

tbf, an O(n) is relatively fast

Body:
I am trying to populate Json downloaded and populate them into an array of objects.  However, there are some complexity on how the data is structured, how would I be able to populate those arrays into objects efficiently?

The following is the basic structure of the Json Data downloaded from a web service:

{
    timestamp: [Date],
    openingStockPrice: [Double],
    closingStockPrice: [Double]
}

E.g.

{
    timestamp: [2019-01-01, 2019-01-02, 2019-01-03....],
    openingStockPrice: [100.0, 101.0, 95.0, ...],
    closingStockPrice: [101.0, 95.0, 99.5, ...]
}

Based on the data structure, there are three separate arrays with data types of dates and double.

Therefore, the first item of each of the arrays belongs to the stock pricing for that particular date.  The second item of each of the arrays belongs to the second day... etc.

Currently, I manage to loop through each of the array and populate the data into objects based on the following structure.

Struct StockPrice {
    timestamp: Date,
    openingStockPrice: Double,
    closingStockPrice: Double
}

var stockPrice: [StockPrice]

I manage to organise the data into array of StockPrice objects by looping through each of the arrays separately.  However, looping through each array does not seem efficient at all as the data set becomes large.

Would any one know, possibly, another way to populate multiple arrays into one array of StockPrice objects (in this scenario)?

Body:
Whatever you do, you would still have to iterate through your multiple arrays because you have to fetch each item. I doubt you can find a O(logN) solution because of the nature of the problem. The best is a O(n)

O(n) solution:

var stockPrices = [StockPrice]()

//assuming timeStamps, openingStockPrices, closingStockPrices have the same number of elements
for i in 0 ..< timeStamps.count {
    let timeStamp = timeStamps[i]
    let openingStockPrice = openingStockPrice[i]
    let closingStockPrice = closingStockPrice[i]
    let stockPrice = StockPrice(timeStamp, openingStockPrice, closingStockPrice)
    stockPrices(add: stockPrice)
}

tbf, an O(n) is relatively fast


问:
Update data using Javascript ajax async failed
I am using HTML, javascript and Nodejs code to develop chrome extension.
On page load, I am calling the function getBalance() to get data and bind it to the HTML span. Following is my code:

```<code>function getBalance() {
    var request = new XMLHttpRequest();
    request.open('GET', 'http://xxx.xxx.xx.xxx:xxxx/getAccount?address=xxxxxxxxxxxxxxxxxxxx', true);
    request.onload = function () {
      var data = JSON.parse(this.response);
      if (request.status >= 200 && request.status < 400) {
        var bal = data.Balance;
        var etherprice = bal / 1000000000000000000;
        document.getElementById("accbal").innerHTML = etherprice;
      } else {
        console.log('error');
      }
    }
    request.send(null);
}

window.addEventListener('load', function load(event){
    getBalance();
});

function sendTransactionBroadcast(result){
    var doAjax = function() {
    $.ajax({
    type : "POST",
    url : "http://xxx.xxx.xx.xxx:xxxx/broadcast",
    data: JSON.stringify(result),
    contentType: 'text/plain; charset=UTF-8',
    success:function(json){
      console.log(json);
      getBalance();
    },
    error: function() {
    alert("Error");
    }
    });
    }
    doAjax();
    }
</code>```

sendTransactionBroadcast() function is called on button click, this function is having ajax async POST call. After its execution complete, On success, I want updated data from getBalance() function and bind it to the span. So, I am calling it again on ajax success. Problem is, if I set debugger and debug the code line by line, I get the updated data in span innerHTML. Everything goes fine. But, if I close debugger, and click the button the span innerHTML is not getting changed on UI. I am not getting the reason why? Also sometimes it changed sometimes not.
Is this ajax async response issue or something else? How to solve this?

manifest.json

```<code>{
  "manifest_version": 2,

  "name": "C Wallet",
  "description": "The C Wallet in your browser",
  "version": "1.0",

  "browser_action": {
   "default_icon": "Image/CI_logo-01.png",
   "default_popup": "popup.html"
  },
  "icons": { "16": "Image/CI_logo-01.png",
    "48": "Image/CI_logo-01.png",
   "128": "Image/CI_logo-01.png"
  },
  "permissions": [
   "activeTab"
   ]
}
</code>```

答: Well, I found the problem. As I was using HTML button type="submit" which was the reason that the page was getting load and the data was not getting changed according to what I was setting. It was getting reset. To avoid page load I used button type="button" and all problems got solved.

Body:
I am using HTML, javascript and Nodejs code to develop chrome extension.
On page load, I am calling the function getBalance() to get data and bind it to the HTML span. Following is my code:

function getBalance() {
    var request = new XMLHttpRequest();
    request.open('GET', 'http://xxx.xxx.xx.xxx:xxxx/getAccount?address=xxxxxxxxxxxxxxxxxxxx', true);
    request.onload = function () {
      var data = JSON.parse(this.response);
      if (request.status >= 200 && request.status < 400) {
        var bal = data.Balance;
        var etherprice = bal / 1000000000000000000;
        document.getElementById("accbal").innerHTML = etherprice;
      } else {
        console.log('error');
      }
    }
    request.send(null);
}

window.addEventListener('load', function load(event){
    getBalance();
});

function sendTransactionBroadcast(result){
    var doAjax = function() {
    $.ajax({
    type : "POST",
    url : "http://xxx.xxx.xx.xxx:xxxx/broadcast",
    data: JSON.stringify(result),
    contentType: 'text/plain; charset=UTF-8',
    success:function(json){
      console.log(json);
      getBalance();
    },
    error: function() {
    alert("Error");
    }
    });
    }
    doAjax();
    }

sendTransactionBroadcast() function is called on button click, this function is having ajax async POST call. After its execution complete, On success, I want updated data from getBalance() function and bind it to the span. So, I am calling it again on ajax success. Problem is, if I set debugger and debug the code line by line, I get the updated data in span innerHTML. Everything goes fine. But, if I close debugger, and click the button the span innerHTML is not getting changed on UI. I am not getting the reason why? Also sometimes it changed sometimes not.
Is this ajax async response issue or something else? How to solve this?

manifest.json

{
  "manifest_version": 2,

  "name": "C Wallet",
  "description": "The C Wallet in your browser",
  "version": "1.0",

  "browser_action": {
   "default_icon": "Image/CI_logo-01.png",
   "default_popup": "popup.html"
  },
  "icons": { "16": "Image/CI_logo-01.png",
    "48": "Image/CI_logo-01.png",
   "128": "Image/CI_logo-01.png"
  },
  "permissions": [
   "activeTab"
   ]
}


问:
Is HAML a Better Tool for Experienced Ruby/Rails Developers?
One of the joys of being a new Ruby on Rails student/developer is the constant discovery of new Gems to make my life more fun or easier. Recently, I "discovered" HAML, which appears to be a fantastic tool for making ERB code even more readable than it already is. However, I wonder if it is a good idea for newer developers, like myself, to embrace a tool like HAML early on, or if it would be smarter to hold off until my expertise in plain Ruby / Rails code has matured. My worry, I suppose, is that embracing a tool like HAML too early might impede my full understanding of Ruby through the coding "shortcuts" it offers. What do you experienced coders say? </p>

答:
It's not so much that taking the HAML route will offer you a shortcut, because it's not like HAML is abstracting anything(other than HTML) that you might miss otherwise. HAML is a substitution for ERB, not an abstraction.

With that being said, I think it's completely up to you. If you haven't learned either, I would scope out both and see which one you like better. I know some people who prefer HAML, and some people who prefer ERB.

One other thing to point out is that a lot of code out there is in ERB, so at least getting the general gist of ERB would be helpful to read other code.


问:
How to use localStorage Carefully in Angular
Since localStorage data can be changed easily, how can we make access controls and more things secure in the Angular App.

Suppose our localstorage contains:

data - {name:user, account_status:inactive,...}

The user can easily change the account_status from inactive to active and get all access.
I am not just concerned about access control but also the other localstorage data which is used in angular.

Can I encrypt the data from the node server and store it in localstorage and decrypt it back when i want to use with the same secret key. Will this have some adverse effects.

Please suggest some methods which can be used.

答: The type data you are trying to store should never to stored on local-storage, especially for a serious production app. Data should always be hashed/encrypted on the server and then sent to the front end for further manipulation.</p>


问:
Uncaught TypeError: Cannot read property 'str' of undefined
I have a variable that is outputting content when I do a console.log, however when I try to do a .str.replace operation on this variable it says it is undefined!

```<code>var thisbuttonDownContents = document.getElementById("Frm" + frm + 'Results');

if (thisbuttonDownContents != null) {
  thisbuttonDownContents = thisbuttonDownContents.textContent;
  console.log(thisbuttonDownContents); //This outputs: West Ter -  Selected
  var test = thisbuttonDownContents.textContent.str.replace("Selected", "");
  //^ This gives the error: Uncaught TypeError: Cannot read property 'str' of undefined
</code>```

I have another function in this javascript that I have copied and pasted this code from and it works fine!  The fact that console.log actually returns a value shows that the element exists and is not undefined. I have tried typecasting toString and that makes no difference.

答:
In this line

```<code>thisbuttonDownContents = thisbuttonDownContents.textContent;
</code>```

you are replacing the DOM element you previously had by the string contained in the DOM element's textContent property.

Obviously  thisbuttonDownContents then is no longer a DOM element, so it doesn't have a  textContent property any longer.

But even if you wipe out that line, replace is a function that is called directly on a variable containing a string, or a string literal, so, as others pointed out, it would have to be

```<code>var test = thisbuttonDownContents.textContent.replace("Selected","");
</code>```

or, if you insist on the problematic line mentioned in the introduction,

```<code>var test = thisbuttonDownContents.replace("Selected","");
</code>```

Body:
I have a variable that is outputting content when I do a console.log, however when I try to do a .str.replace operation on this variable it says it is undefined!

var thisbuttonDownContents = document.getElementById("Frm" + frm + 'Results');

if (thisbuttonDownContents != null) {
  thisbuttonDownContents = thisbuttonDownContents.textContent;
  console.log(thisbuttonDownContents); //This outputs: West Ter -  Selected
  var test = thisbuttonDownContents.textContent.str.replace("Selected", "");
  //^ This gives the error: Uncaught TypeError: Cannot read property 'str' of undefined

I have another function in this javascript that I have copied and pasted this code from and it works fine!  The fact that console.log actually returns a value shows that the element exists and is not undefined. I have tried typecasting toString and that makes no difference.

Body:
In this line

thisbuttonDownContents = thisbuttonDownContents.textContent;

you are replacing the DOM element you previously had by the string contained in the DOM element's textContent property.

Obviously  thisbuttonDownContents then is no longer a DOM element, so it doesn't have a  textContent property any longer.

But even if you wipe out that line, replace is a function that is called directly on a variable containing a string, or a string literal, so, as others pointed out, it would have to be

var test = thisbuttonDownContents.textContent.replace("Selected","");

or, if you insist on the problematic line mentioned in the introduction,

var test = thisbuttonDownContents.replace("Selected","");


答:
I have made it work very similar to the answer from Saurabh with the following:

```<code><html>
<head>
   <style>
   .done
   {
       text-decoration:line-through;
   }
   </style>
</head>
<body>
<input type="text" id="user_input">
<ul id="list"></ul>

<script>

var input = document.getElementById("user_input");

function addingNewList()
{
  var li = document.createElement("li");
  var tag = document.createElement("a");
  tag.appendChild(document.createTextNode(input.value));

  var ul = document.getElementById("list");

  li.appendChild(tag);
  ul.appendChild(li);

  tag.addEventListener("click",function()
  {
    toggleClass(this);
  })
}

function toggleClass(e) {
  e.classList.toggle("done");
}

function input_length()
{
    return input.value.length;
}
input.addEventListener("keypress",function(event)
{
    if(input_length() >0 && event.which == 13)
    {
        addingNewList();
    }
})
</script>
</body>
</html>
</code>```

In the above example in your question you had spelt getElementById wrong in one place and you did not define ul. I also added the toggle function to add to the click event you need to create.

Title: Can't create "a" element on clicking and subsequently classList.toggle() not working

Body:
I am making a to-do list application. You enter an item. It gets appended to the list. On clicking the item on the list, it gets crossed. Can't make the text clickable and thus can't add the classList.toggle() function to cross the item from the list.

I've tried to create an empty "li" element to which an "a" element is created inside it. (Note: all this happens when we add the item to the list). I thought, using the "a" element, I could hover over the text and thus make it clickable and connect it to the classList.toggle() function.

<input type="text" id="user_input">

The expected output should be that, if the user add: "Do Laundry" to the list, It gets added to the list. On clicking "Do Laundry", there should be line through it, i.e it should be crossed. Currently, the items are getting added, but are not getting crossed. No error message is showing up either.

Body:
I have made it work very similar to the answer from Saurabh with the following:

<html>
<head>
   <style>
   .done
   {
       text-decoration:line-through;
   }
   </style>
</head>
<body>
<input type="text" id="user_input">
<ul id="list"></ul>

<script>

var input = document.getElementById("user_input");

function addingNewList()
{
  var li = document.createElement("li");
  var tag = document.createElement("a");
  tag.appendChild(document.createTextNode(input.value));

  var ul = document.getElementById("list");

  li.appendChild(tag);
  ul.appendChild(li);

  tag.addEventListener("click",function()
  {
    toggleClass(this);
  })
}

function toggleClass(e) {
  e.classList.toggle("done");
}

function input_length()
{
    return input.value.length;
}
input.addEventListener("keypress",function(event)
{
    if(input_length() >0 && event.which == 13)
    {
        addingNewList();
    }
})
</script>
</body>
</html>

In the above example in your question you had spelt getElementById wrong in one place and you did not define ul. I also added the toggle function to add to the click event you need to create.


问:
CSS scrollbar not working outside of Chrome?
I'm using this CSS code in order to customize my scroll bar style:

```<code>::-webkit-scrollbar {
      width: 8px;
} /* this targets the default scrollbar (compulsory) */

::-webkit-scrollbar-track {
      background-color: black;
} /* the new scrollbar will have a flat appearance with the set background color */

::-webkit-scrollbar-thumb {
      background-color: #59e5f6;
      border-radius: 10px;
} /* this will style the thumb, ignoring the track */

::-webkit-scrollbar-button {
      background-color: black;
} /* optionally, you can style the top and the bottom buttons (left and right for horizontal bars) */

::-webkit-scrollbar-corner {
      background-color: black;
} /* if both the vertical and the horizontal bars appear, then perhaps the right bottom corner also needs to be styled */

body {
    scrollbar-face-color: black;
}
</code>```

It works great on Chrome, but not other browsers.

Do you have any idea how to fix that?

答:
It's not supported in IE, Edge and Firefox by default.
Here is screenshot from documentation
https://developer.mozilla.org/en-US/docs/Web/CSS/::-webkit-scrollbar

Note: You can use javascript libraries like
perfect-scrollbar

Body:
I'm using this CSS code in order to customize my scroll bar style:

::-webkit-scrollbar {
      width: 8px;
} /* this targets the default scrollbar (compulsory) */

::-webkit-scrollbar-track {
      background-color: black;
} /* the new scrollbar will have a flat appearance with the set background color */

::-webkit-scrollbar-thumb {
      background-color: #59e5f6;
      border-radius: 10px;
} /* this will style the thumb, ignoring the track */

::-webkit-scrollbar-button {
      background-color: black;
} /* optionally, you can style the top and the bottom buttons (left and right for horizontal bars) */

::-webkit-scrollbar-corner {
      background-color: black;
} /* if both the vertical and the horizontal bars appear, then perhaps the right bottom corner also needs to be styled */

body {
    scrollbar-face-color: black;
}

It works great on Chrome, but not other browsers.

Do you have any idea how to fix that?


问:
How to test a code that invokes Instant.now() with JUnit 5?
I have a code that looks somehow like this:

```<code>MyObject getMyObject() {
    Instant now = Instant.now();
    return myService.doSomething(now);
}
</code>```

I know that PowerMock is not supported in JUnit 5, but I am wondering maybe there is a solution at least for standard API like dates.

Right now I am mocking the Instant instance with Mockito.any() which is incorrect as my test won't fail if I pass a wrong Instant.

答:
You can move the creation of current Instant to a package level method:

```<code>MyObject getMyObject() {
    Instant now = getCurrentInstance();
    return myService.doSomething(now);
}

Instant getCurrentInstant(){
  Instant.now();
}
</code>```

Then in your test you can spy on the SUT and mock the getCurrentInstant method:

```<code>Sut sut = spy(new Sut());
doReturn(testInstance).when(sut).getCurrentInstant();

sut.getMyObject();
</code>```

Here is an article I wrote on Mockito Spying if you need a further read.

Body:
I have a code that looks somehow like this:

MyObject getMyObject() {
    Instant now = Instant.now();
    return myService.doSomething(now);
}

I know that PowerMock is not supported in JUnit 5, but I am wondering maybe there is a solution at least for standard API like dates.

Right now I am mocking the Instant instance with Mockito.any() which is incorrect as my test won't fail if I pass a wrong Instant.

Body:
You can move the creation of current Instant to a package level method:

MyObject getMyObject() {
    Instant now = getCurrentInstance();
    return myService.doSomething(now);
}

Instant getCurrentInstant(){
  Instant.now();
}

Then in your test you can spy on the SUT and mock the getCurrentInstant method:

Sut sut = spy(new Sut());
doReturn(testInstance).when(sut).getCurrentInstant();

sut.getMyObject();

Here is an article I wrote on Mockito Spying if you need a further read.


问:
list of buttons on the page. After I get the list I want to check if the button is displayed on the page
I am new to automation testing and I have been trying to figure this out all day. Anyways I want to go the site and get a list of buttons on the page. Than I want to print the list of buttons that are displayed on the page.

```<code>package com.practice;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Buttons {

    public static void main(String[] args) throws InterruptedException {

        System.setProperty("webdriver.chrome.driver",
                "C:\\Users\\Oderint dum metuant\\eclipse-workspace\\JAR FILES\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.toolsqa.com/automation-practice-switch-windows/");

        List <WebElement> buttons = driver.findElements(By.tagName("button"));
        for ( int i=0; i<buttons.size();i++){
            WebElement button = buttons.get(i);
            if(button.isEnabled()){
                System.out.println(buttons);
                }
            }

    }

}
</code>```

This is what I get when I run the code:

[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]

答:
There are basically three things

```<code>Thread.sleep(10000); // you can also use web driver's implicit and explicit wait or wait for page to load. This is just for example
List <WebElement> buttons = driver.findElements(By.tagName("button"));
    for (int i=0; i<buttons.size();i++){
        WebElement button = buttons.get(i);
        try {
            if(button.isDisplayed()){
                System.out.println(button.getText()+" - is displayed");
            }
            else {
                System.out.println(button.getText()+" - is present but not displayed");
            }
        } catch(NoSuchElementException e) {
            System.out.println("Element is not present, hence not displayed as well");
        }
    }
</code>```

Use some wait functionality to load the page properly.

Use isDisplayed method to check visibility of button. isDisplayed will throw error when element is not present and visibled. So used try catch block for handling NoSuchElementException exception.

You are printing WebElements object, ie buttons. Use get text method of button and then print it. You can see which button is visible or which is not visible.

Body:
I am new to automation testing and I have been trying to figure this out all day. Anyways I want to go the site and get a list of buttons on the page. Than I want to print the list of buttons that are displayed on the page.

package com.practice;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class Buttons {

    public static void main(String[] args) throws InterruptedException {

        System.setProperty("webdriver.chrome.driver",
                "C:\\Users\\Oderint dum metuant\\eclipse-workspace\\JAR FILES\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.toolsqa.com/automation-practice-switch-windows/");

        List <WebElement> buttons = driver.findElements(By.tagName("button"));
        for ( int i=0; i<buttons.size();i++){
            WebElement button = buttons.get(i);
            if(button.isEnabled()){
                System.out.println(buttons);
                }
            }

    }

}

This is what I get when I run the code:

[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]
[[ChromeDriver: chrome on XP (fddbb691263a84a531368a18e6d495b3)] -> tag name: button]

Body:
There are basically three things

Thread.sleep(10000); // you can also use web driver's implicit and explicit wait or wait for page to load. This is just for example
List <WebElement> buttons = driver.findElements(By.tagName("button"));
    for (int i=0; i<buttons.size();i++){
        WebElement button = buttons.get(i);
        try {
            if(button.isDisplayed()){
                System.out.println(button.getText()+" - is displayed");
            }
            else {
                System.out.println(button.getText()+" - is present but not displayed");
            }
        } catch(NoSuchElementException e) {
            System.out.println("Element is not present, hence not displayed as well");
        }
    }

Use some wait functionality to load the page properly.

Use isDisplayed method to check visibility of button. isDisplayed will throw error when element is not present and visibled. So used try catch block for handling NoSuchElementException exception.

You are printing WebElements object, ie buttons. Use get text method of button and then print it. You can see which button is visible or which is not visible.


问:
Can't cast value of type UIViewController to PatternDetailViewController
Am trying to downcast a view controller to a detail view controller but can't. Am using Core Data (for the first time).
The error is in the prepareForSegue method and reads: "Could not cast value of type 'UIViewController' (0x1b81cdc) to 'Patternz.PatternDetailViewController' (0x32488).
(lldb) "

Would appreciate an explanation of why it doesn't work.
Here are the files.

ViewController.swift

```<code>import UIKit
import CoreData

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    var patterns : [Pattern] = []

    var selectedPattern : Pattern? = nil

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.dataSource = self
        self.tableView.delegate = self

        createTestPatterns()

        var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!

        var request = NSFetchRequest(entityName: "Pattern")

        var results = context.executeFetchRequest(request, error: nil)

        if results != nil {
            self.patterns = results! as! [Pattern]
        }
    }

    func createTestPatterns() {
        var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!

        var pattern = NSEntityDescription.insertNewObjectForEntityForName("Pattern", inManagedObjectContext: context) as! Pattern
        pattern.name = "Dress Shirt"
        pattern.frontimage = UIImageJPEGRepresentation(UIImage(named: "examplePattern.jpg"), 1)
        context.save(nil)
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.patterns.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = UITableViewCell()
        var pattern = self.patterns[indexPath.row]
        cell.textLabel!.text = pattern.name
        cell.imageView!.image = UIImage(data: pattern.frontimage)
        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        self.selectedPattern = self.patterns[indexPath.row]
        self.performSegueWithIdentifier("patternDetailSegue", sender: self)
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "patternDetailSegue" {
            var detailViewController = segue.destinationViewController as! PatternDetailViewController // Could not cast value of type 'UIViewController' to 'Patternz.PatternDetailViewController'
            detailViewController.pattern = self.selectedPattern
        }
    }

}
</code>```

PatternDetailViewController.swift

```<code>import UIKit

class PatternDetailViewController: UIViewController {

    var pattern : Pattern? = nil

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        self.navigationItem.title = self.pattern!.name
    }

}
</code>```

答:
My issue is:

Not work

```<code>let aBCViewController = UIViewController(nibName: "ABCViewController", bundle: nil) as! ABCViewController
present(aBCViewController, animated: true, completion: nil)
</code>```

Work

```<code>let aBCViewController = ABCViewController(nibName: "ABCViewController", bundle: nil)
present(aBCViewController, animated: true, completion: nil)
</code>```

Body:
Am trying to downcast a view controller to a detail view controller but can't. Am using Core Data (for the first time).
The error is in the prepareForSegue method and reads: "Could not cast value of type 'UIViewController' (0x1b81cdc) to 'Patternz.PatternDetailViewController' (0x32488).
(lldb) "

Would appreciate an explanation of why it doesn't work.
Here are the files.

ViewController.swift

import UIKit
import CoreData

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    var patterns : [Pattern] = []

    var selectedPattern : Pattern? = nil

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.tableView.dataSource = self
        self.tableView.delegate = self

        createTestPatterns()

        var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!

        var request = NSFetchRequest(entityName: "Pattern")

        var results = context.executeFetchRequest(request, error: nil)

        if results != nil {
            self.patterns = results! as! [Pattern]
        }
    }

    func createTestPatterns() {
        var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!

        var pattern = NSEntityDescription.insertNewObjectForEntityForName("Pattern", inManagedObjectContext: context) as! Pattern
        pattern.name = "Dress Shirt"
        pattern.frontimage = UIImageJPEGRepresentation(UIImage(named: "examplePattern.jpg"), 1)
        context.save(nil)
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.patterns.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = UITableViewCell()
        var pattern = self.patterns[indexPath.row]
        cell.textLabel!.text = pattern.name
        cell.imageView!.image = UIImage(data: pattern.frontimage)
        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        self.selectedPattern = self.patterns[indexPath.row]
        self.performSegueWithIdentifier("patternDetailSegue", sender: self)
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "patternDetailSegue" {
            var detailViewController = segue.destinationViewController as! PatternDetailViewController // Could not cast value of type 'UIViewController' to 'Patternz.PatternDetailViewController'
            detailViewController.pattern = self.selectedPattern
        }
    }

}

PatternDetailViewController.swift

import UIKit

class PatternDetailViewController: UIViewController {

    var pattern : Pattern? = nil

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        self.navigationItem.title = self.pattern!.name
    }

}

Body:
My issue is:

Not work

let aBCViewController = UIViewController(nibName: "ABCViewController", bundle: nil) as! ABCViewController
present(aBCViewController, animated: true, completion: nil)

Work

let aBCViewController = ABCViewController(nibName: "ABCViewController", bundle: nil)
present(aBCViewController, animated: true, completion: nil)


问:
Support of third party payment methods in B2B apps
Will apple B2B apps support external payment methods instead of In-App purchase? I need to provide upgrades for paid users. The distribution method used is apple-vpp. Since apple takes 30% commission for in-app purchase, I want to know wether we can add third party payments for apps distributed via apple-vpp. </p>

答:
Apple does not allow third party payment integrations if there is no physical exchange of goods or services. If your application only allows some features only after some subscription then the apple is going to reject the application. If you are paying someone in return of any physical goods like shopping applications or in return of some services then the application can user third party payment methods.

Please refer below link

https://forums.developer.apple.com/thread/97423


问:
How to fix this up? " Unknown action The action 'index' could not be found for UsersController"
When I go to my localhost:3000/users page, I get:

Unknown action

The action 'index' could not be found for UsersController.

答:
First you need to make sure that your controller actually has an index action, so

class UsersController < ApplicationController has to include the def index ... end in it.
Also, make sure your routes are set up correctly using

```<code>resources :users
</code>```

and check it by typing

```<code>rake routes
</code>```

in the terminal to check that the routes are right.
You might also want to check that the root is set up correctly in the config/routes.rb file

Body:
First you need to make sure that your controller actually has an index action, so

class UsersController < ApplicationController has to include the def index ... end in it.
Also, make sure your routes are set up correctly using

resources :users

and check it by typing

rake routes

in the terminal to check that the routes are right.
You might also want to check that the root is set up correctly in the config/routes.rb file


问:
"Error: Cannot find module '@app/foo'" in prod mode when using libs
I have a project where I built several modules. After finding that nestjs has a lib cli command I ported all of them to use this style.
Now my app can't find these modules when using npm run start:prod.

```<code>Error: Cannot find module '@app/foo'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
    at Function.Module._load (internal/modules/cjs/loader.js:508:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous> (/Users/xxx/Development/nest-test/dist/src/app.service.js:13:15)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
</code>```

I created a project with the basic code and one library to reproduce the problem: https://github.com/hkeio/nestjs-test

Even when I link the package node is not able to find the module.

```<code>cd libs/foo
npm link
cd ../..
npm link @app/foo
</code>```

When running NODE_DEBUG=* npm run start:prod I can see that he is looking at the right place but does not find the module:

```<code>MODULE 12494: looking for "@app/foo" in [
    "/Users/xxx/Development/nest-test/dist/src/node_modules",
    "/Users/xxx/Development/nest-test/dist/node_modules",
    "/Users/xxx/Development/nest-test/node_modules",
    "/Users/xxx/Development/node_modules",
    "/Users/xxx/node_modules",
    "/Users/node_modules",
    "/node_modules",
    "/Users/xxx/.node_modules",
    "/Users/xxx/.node_libraries",
    "/Users/xxx/.nvm/versions/node/v10.15.3/lib/node"
]

...

$ pwd
/Users/xxx/Development/nest-test/node_modules
$ ll @app
total 0
drwxr-xr-x    3 xxx  staff     96 May 30 09:04 .
drwxr-xr-x  608 xxx  staff  19456 May 30 09:04 ..
lrwxr-xr-x    1 xxx  staff     65 May 30 09:04 foo -> ../../../../.nvm/versions/node/v10.15.3/lib/node_modules/@app/foo```
```

答:
According to the docs of tsconfig-paths it can be used when executing the built sources with node.
The issue comment you are referencing also mentions execution with node.

Actually the problem occurs when executing the built files with node dist/main.js, not during the build process with tsc.

I managed to get a working solution by following theses instructions from tsconfig-paths docs. @bisonfoutu created an example repo here.

Add a file named tsconfig-paths-bootstrap.js to the root of the project, and paste the code from the docs in it.

Change the start:prod script to: node -r ./tsconfig-paths-bootstrap.js dist/main.js

You should now be able to compile and execute the project with TS paths. (be aware that you will not be able to compile if there is no path set in tsconfig.json)

Body:
I have a project where I built several modules. After finding that nestjs has a lib cli command I ported all of them to use this style.
Now my app can't find these modules when using npm run start:prod.

Error: Cannot find module '@app/foo'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
    at Function.Module._load (internal/modules/cjs/loader.js:508:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous> (/Users/xxx/Development/nest-test/dist/src/app.service.js:13:15)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)

I created a project with the basic code and one library to reproduce the problem: https://github.com/hkeio/nestjs-test

Even when I link the package node is not able to find the module.

cd libs/foo
npm link
cd ../..
npm link @app/foo

When running NODE_DEBUG=* npm run start:prod I can see that he is looking at the right place but does not find the module:

MODULE 12494: looking for "@app/foo" in [
    "/Users/xxx/Development/nest-test/dist/src/node_modules",
    "/Users/xxx/Development/nest-test/dist/node_modules",
    "/Users/xxx/Development/nest-test/node_modules",
    "/Users/xxx/Development/node_modules",
    "/Users/xxx/node_modules",
    "/Users/node_modules",
    "/node_modules",
    "/Users/xxx/.node_modules",
    "/Users/xxx/.node_libraries",
    "/Users/xxx/.nvm/versions/node/v10.15.3/lib/node"
]

...

$ pwd
/Users/xxx/Development/nest-test/node_modules
$ ll @app
total 0
drwxr-xr-x    3 xxx  staff     96 May 30 09:04 .
drwxr-xr-x  608 xxx  staff  19456 May 30 09:04 ..
lrwxr-xr-x    1 xxx  staff     65 May 30 09:04 foo -> ../../../../.nvm/versions/node/v10.15.3/lib/node_modules/@app/foo```


问:
Create Android App That Acts As A Shortcut To Our Mobile Site
We have a special mobile version of our site that we would like to promote in the android marketplace.  The "app" would effectively be a shortcut to the website, but you would be able to download it and have an icon for it, just like any other app.

Is this possible?  If so, can you link me to instructions?  I was not able to find any info searching google.

Thanks,
Jonah

答:
Just make a single Activity that hosts a single WebView and preload it with your URL it's really easy.

I have a similar App and did this.

ContentLicense: CC BY-SA 2.5


问:
Can't connect to Github's website in Chrome but it works when I use Firefox
https://i.imgur.com/qKyu744.jpg

This started happening just a few days ago. I can access the site on the same computer in Firefox. Not sure why it is telling me that the site is insecure, but that must be related. I tried ipconfig /flushdns, deleting my cookies, and disabling my firewall but none of those fixed it. Can't find any solutions online either so far. Using the latest Chrome update and Windows 10. Please help!

Edit: Solved my issue by installing this Windows update:
https://support.microsoft.com/en-us/help/4284835

答: If CORS extension has been downloaded and enabled in the Chrome browser then disable the CORS(Allow-control-Allow-origin) extension. It will work..!</p>


问:
How do I use Postgres's to_char in a jOOQ query?
I am trying to convert the following PostgreSQL query to jOOQ:

SELECT count(*), to_char(created_date, 'YYYY-MM-DD') as year_month_date
  FROM log
  GROUP BY year_month_date
  ORDER BY year_month_date
```

<p>What I have is:</p>

<pre class="lang-java prettyprint-override"><code>jooq.select(
    DSL.count(),
    DSL.field("to_char(created_date, 'YYYY-MM-DD') as year_month_date")
  )
  .from(LOG)
  .groupBy(DSL.field("year_month_date"))
  .orderBy(DSL.field("year_month_date"))
  .fetch();
</code>```

Is there a way to do using jOOQ's fluent API so I don't have to use strings?

答:
Using TO_CHAR()

There is a pending feature request to add support for vendor specific to_char() functions: https://github.com/jOOQ/jOOQ/issues/8381

In order to standardise on such a function, more research needs to be done to be sure we can cover everything each vendor implements here, as the formatting logic is unfortunately quite vendor specific, and stringly typed.

So, if you want to use to_char(), currently, you will have to resort to using plain SQL templating, which you already did. You could obviously factor out this utility in a reusable form, such as:

```<code>public static Field<String> toChar(Field<?> date, String format) {
    return DSL.field("to_char({0}, {1})", SQLDataType.VARCHAR, date, DSL.inline(format));
}
</code>```

Truncating dates

Of course, in your particular query, you could also resort to using standard SQL features, such as CAST(). I think that what you're trying to do is truncate time information from your timestamp or timestamptz column, so you could do this instead:

SELECT count(*), CAST (created_date AS DATE) d
  FROM log
  GROUP BY d
  ORDER BY d
```

<p>Or with jOOQ:</p>

<pre class="lang-java prettyprint-override"><code>Field<Date> d = LOG.CREATED_DATE.cast(SQLDataType.DATE);

jooq.select(count(), d)
    .from(LOG)
    .groupBy(d)
    .orderBy(d)
    .fetch();
</code>```

Body:
I am trying to convert the following PostgreSQL query to jOOQ:

SELECT count(*), to_char(created_date, 'YYYY-MM-DD') as year_month_date
  FROM log
  GROUP BY year_month_date
  ORDER BY year_month_date

What I have is:

jooq.select(
    DSL.count(),
    DSL.field("to_char(created_date, 'YYYY-MM-DD') as year_month_date")
  )
  .from(LOG)
  .groupBy(DSL.field("year_month_date"))
  .orderBy(DSL.field("year_month_date"))
  .fetch();

Is there a way to do using jOOQ's fluent API so I don't have to use strings?

Body:
Using TO_CHAR()

There is a pending feature request to add support for vendor specific to_char() functions: https://github.com/jOOQ/jOOQ/issues/8381

In order to standardise on such a function, more research needs to be done to be sure we can cover everything each vendor implements here, as the formatting logic is unfortunately quite vendor specific, and stringly typed.

So, if you want to use to_char(), currently, you will have to resort to using plain SQL templating, which you already did. You could obviously factor out this utility in a reusable form, such as:

public static Field<String> toChar(Field<?> date, String format) {
    return DSL.field("to_char({0}, {1})", SQLDataType.VARCHAR, date, DSL.inline(format));
}

Truncating dates

Of course, in your particular query, you could also resort to using standard SQL features, such as CAST(). I think that what you're trying to do is truncate time information from your timestamp or timestamptz column, so you could do this instead:

SELECT count(*), CAST (created_date AS DATE) d
  FROM log
  GROUP BY d
  ORDER BY d

Or with jOOQ:

Field<Date> d = LOG.CREATED_DATE.cast(SQLDataType.DATE);

jooq.select(count(), d)
    .from(LOG)
    .groupBy(d)
    .orderBy(d)
    .fetch();


问:
psycopg2: can't adapt type 'numpy.int64'
I have a dataframe with the dtypes shown below and I want to insert the dataframe into a postgres DB but it fails due to error can't adapt type 'numpy.int64'

```<code>id_code               int64
sector              object
created_date         float64
updated_date    float64
</code>```

How can I convert these types to native python types such as from int64 (which is essentially 'numpy.int64') to a classic int that would then be acceptable to postgres via the psycopg2 client.

```<code>data['id_code'].astype(np.int)  defaults to int64
</code>```

It is nonetheless possible to convert from one numpy type to another (e.g from int to float)

```<code>data['id_code'].astype(float)
</code>```

changes to

```<code>dtype: float64
</code>```

The bottomline is that psycopg2 doesn't seem to understand numpy datatypes if any one has ideas how to convert them to classic types that would be helpful.

Updated: Insertion to DB

```<code>def insert_many():
    """Add data to the table."""
    sql_query = """INSERT INTO classification(
                id_code, sector, created_date, updated_date)
                VALUES (%s, %s, %s, %s);"""
    data = pd.read_excel(fh, sheet_name=sheetname)
    data_list = list(data.to_records())

    conn = None
    try:
        conn = psycopg2.connect(db)
        cur = conn.cursor()
        cur.executemany(sql_query, data_list)
        conn.commit()
        cur.close()
    except(Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()
</code>```

答:
Add below somewhere in your code:</p>

```<code>import numpy
from psycopg2.extensions import register_adapter, AsIs
def addapt_numpy_float64(numpy_float64):
    return AsIs(numpy_float64)
def addapt_numpy_int64(numpy_int64):
    return AsIs(numpy_int64)
register_adapter(numpy.float64, addapt_numpy_float64)
register_adapter(numpy.int64, addapt_numpy_int64)
</code>```

Body:
I have a dataframe with the dtypes shown below and I want to insert the dataframe into a postgres DB but it fails due to error can't adapt type 'numpy.int64'

id_code               int64
sector              object
created_date         float64
updated_date    float64

How can I convert these types to native python types such as from int64 (which is essentially 'numpy.int64') to a classic int that would then be acceptable to postgres via the psycopg2 client.

data['id_code'].astype(np.int)  defaults to int64

It is nonetheless possible to convert from one numpy type to another (e.g from int to float)

data['id_code'].astype(float)

changes to

dtype: float64

The bottomline is that psycopg2 doesn't seem to understand numpy datatypes if any one has ideas how to convert them to classic types that would be helpful.

Updated: Insertion to DB

def insert_many():
    """Add data to the table."""
    sql_query = """INSERT INTO classification(
                id_code, sector, created_date, updated_date)
                VALUES (%s, %s, %s, %s);"""
    data = pd.read_excel(fh, sheet_name=sheetname)
    data_list = list(data.to_records())

    conn = None
    try:
        conn = psycopg2.connect(db)
        cur = conn.cursor()
        cur.executemany(sql_query, data_list)
        conn.commit()
        cur.close()
    except(Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()

Body:
Add below somewhere in your code:

import numpy
from psycopg2.extensions import register_adapter, AsIs
def addapt_numpy_float64(numpy_float64):
    return AsIs(numpy_float64)
def addapt_numpy_int64(numpy_int64):
    return AsIs(numpy_int64)
register_adapter(numpy.float64, addapt_numpy_float64)
register_adapter(numpy.int64, addapt_numpy_int64)