问:
spring boot how to set securitycontext for scheduled task to call secured method?
I'm trying to use a @scheduled task to update some data in my database.

```<code>@Scheduled()
public void update() {
  sync()
}

public void sync() {
   if (SecurityContextHolder.getContext()
      .getAuthentication().getAuthorities().stream.matchAny(r-> ROLE_ADMIN)) {
...
    } else {
    ...
    }
}
</code>```

The securityContext is null once the scheduled task runs. Without removing permission validation, how do I set the securityContext of the scheduled task to Admin?

答:
The SecurityContext is stored in the ThreadLoacal. You can use the following codes to create a fake admin user and set it to the SecurityContext before running sync() :

List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

//This is the permission that the admin should have. It depends on your application security configuration.
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

// Here it does not matter what values username and password are.
// Just ensure this user has the the Admin GrantedAuthority and his account is enabled
User user = new User("admin", "password", true, true, true, true, grantedAuthorities);

Authentication authentication = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);

```
<p>If the thread that executes sync() is dedicated for the scheduled task to run only , you can keep that thread to has this fake admin user. Otherwise , you need to clear this fake admin user from the <code>ThreadLocal</code> after running sync() :</p>
<pre class="lang-java prettyprint-override"><code>SecurityContextHolder.clearContext();
</code>```

Body:
I'm trying to use a @scheduled task to update some data in my database.

@Scheduled()
public void update() {
  sync()
}

public void sync() {
   if (SecurityContextHolder.getContext()
      .getAuthentication().getAuthorities().stream.matchAny(r-> ROLE_ADMIN)) {
...
    } else {
    ...
    }
}

The securityContext is null once the scheduled task runs. Without removing permission validation, how do I set the securityContext of the scheduled task to Admin?

Body:
The SecurityContext is stored in the ThreadLoacal. You can use the following codes to create a fake admin user and set it to the SecurityContext before running sync() :

List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

//This is the permission that the admin should have. It depends on your application security configuration.
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

// Here it does not matter what values username and password are.
// Just ensure this user has the the Admin GrantedAuthority and his account is enabled
User user = new User("admin", "password", true, true, true, true, grantedAuthorities);

Authentication authentication = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);

If the thread that executes sync() is dedicated for the scheduled task to run only , you can keep that thread to has this fake admin user. Otherwise , you need to clear this fake admin user from the ThreadLocal after running sync() :

SecurityContextHolder.clearContext();


来源: stackexchange

问:
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

ContentLicense: CC BY-SA 4.0

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:
try the following:

from  pyspark.sql import functions as F
data = [(("ID1", 3, 5)), (("ID2", 4, 12)), (("ID3", 8, 3))]
df = spark.createDataFrame(data, ["ID", "colA", "colB"])
df.withColumn('max_col',
   F.when(F.col('colA') > F.col('colB'), 'colA').
     otherwise('colB')).show()

Yields:

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


问:
Google Play warning: Your app contains a Cross-App Scripting Vulnerability
Good day all,

I got a email from google play regarding Cross-App Scripting Vulnerability in one or more my published apps. I am using WebView in my apps, so they says my app contains webView Cross-App Scripting issue which can allow malicious apps to steal user cookies and other data. And They give what action I am going to take, that is

Action required

Please follow the steps below to fix the issue with your apps (listed at the end of this email). You can refer to the notice in your Play Console for the deadline to fix this problem. After this deadline, updates to affected apps will be blocked if the vulnerability is still present. Your published APK version will remain unaffected.
     Additional details

WebViews that enable JavaScript and load data read from untrusted Intents can be tricked by malicious apps into executing JavaScript code in an unsafe context. You should prevent this vulnerability in one of the following ways:

Option 1: Ensure that affected activities are not exported

Find any Activities with affected WebViews. If these Activities do not need to take Intents from other apps you can set android:exported=false for the Activities in your Manifest. This ensures that malicious apps cannot send harmful inputs to any WebViews in these Activities.

Option 2: Protect WebViews in exported activities

If you want to set an Activity with an affected WebView as exported then we recommend that you make the following changes:

Update your targetSdkVersion

Ensure that your targetSdkVersion meets Google Play's target API level requirement. Apps with a targetSdkVersion of 16 or lower evaluate JavaScript URLs passed to loadUrl in the currently loaded page context. Targeting SDK version 16 or lower and calling loadUrl using unsanitized input from untrusted Intents lets attackers execute harmful scripts in the affected WebView.

Protect calls to evaluateJavascript

Ensure that parameters to evaluateJavascript are always trusted. Calling evaluateJavascript using unsanitized input from untrusted Intents lets attackers execute harmful scripts in the affected WebView.

Prevent unsafe file loads

Ensure that affected WebViews cannot load the cookie database. WebViews that load unsanitized file:// URLs from untrusted Intents can be attacked by malicious apps in the following way. A malicious web page can write script tags into the cookies database and then a malicious app can send an Intent with a file:// URL pointing to your WebView cookies database. The malicious script will execute if the cookies database is loaded in a WebView and can steal session information.

You can ensure that affected WebViews cannot load the WebView cookies database in two ways. You can either disable all file access or you can verify that any loaded file:// URLs point to safe files. Note that an attacker can use a symbolic link to trick checks on the URL path. To prevent such an attack, be sure to check the canonical path of any untrusted file:// URL before loading instead of just checking the URL path.

So my question is

If I make the changes mentioned in the email, how that will affect my apps?

Does any feature of my app will disabled ?

答:
```<code>After a lot of struggle, below things worked for me

 mWebView.getSettings().setAppCacheMaxSize(0);
 mWebView.getSettings().setAllowFileAccess(false);
 mWebView.getSettings().setAppCacheEnabled(false);

<meta-data android:name="android.webkit.WebView.EnableSafeBrowsing"
android:value="true" />
</code>```


问:
Only part of img is clickable inside an anchor tag in chrome
I have the following code. Only part of the image is clickable.

HTML

```<code><div class="row">
  <div class="col-md-4 text-center">
    <div class="portfolio-item">
      <a>
        <img class="btn img-portfolio project-img-responsive" data-toggle="modal" data-target="#project-modal" src="img/map_image.jpg">
      </a>
    </div>
  </div>
</div>
</code>```

CSS

```<code>.btn -> bootstrap CSS class
.row -> bootstrap CSS class
.col-md-4 -> bootstrap CSS class
.text-center -> bootstrap CSS class
.img-portfolio {
  margin: 0 auto;
}

.project-img-responsive {
    display: block;
    max-width: 50%;
    height: auto;
}
.portfolio-item {
  margin-bottom: 25px;
}
</code>```

The problem is only with chrome. Works fine in mozilla.

What property am I missing out or getting wrong?

答:
Given that the JS fiddle works fine, I suspect another (invisible) element on the page is overlapping your image. I managed to fix a problem similar to this by setting the z-index and position (because the first won't work without the second) of the  tag...

```<code>position: relative;
z-index: 100;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following code. Only part of the image is clickable.

HTML

CSS

.btn -> bootstrap CSS class
.row -> bootstrap CSS class
.col-md-4 -> bootstrap CSS class
.text-center -> bootstrap CSS class
.img-portfolio {
  margin: 0 auto;
}

.project-img-responsive {
    display: block;
    max-width: 50%;
    height: auto;
}
.portfolio-item {
  margin-bottom: 25px;
}

The problem is only with chrome. Works fine in mozilla.

What property am I missing out or getting wrong?

Body:
Given that the JS fiddle works fine, I suspect another (invisible) element on the page is overlapping your image. I managed to fix a problem similar to this by setting the z-index and position (because the first won't work without the second) of the <a> tag...

position: relative;
z-index: 100;


问:
Split a string based on colon and new line and add the result to dicitonary
I want to convert the below unicode in python to a dictionary:

```<code>Version: 67
Build Number: 123master
Project Name: git+ssh://git@stash.xyz.com:1999/ns/x-y.git
Git Url: origin/master
Git Branch: 0223445as5njn34nfk6kg
perforce_url:
  //project//url//
artifacts:
  "./": "./"
exclude:
  - manifest.yml
  - node_modules
  - RPMS
  - .git
  - build-toolbox

</code>```

```<code>>>> x
' Version: 67\nBuild Number: 123master\nProject Name: git+ssh://git@stash.xyz.com:1999/ns/x-y.git\nGit Url: origin/master\nGit Branch: 0223445as5njn34nfk6kg\nperforce_url:\n  //project//url//\nartifacts:\n  "./": "./"\nexclude:\n  - manifest.yml\n  - node_modules\n  - RPMS\n  - .git\n  - build-toolbox '
>>>
>>>
>>> dict(map(lambda x: x.split(':'), x.splitlines()))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #2 has length 4; 2 is required

</code>```

```<code>
dict(item.split(":") for item in x.splitlines())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #2 has length 4; 2 is required

</code>```

I believe the problem is with the following item

```<code>Project Name: git+ssh://git@stash.xyz.com:1999/ns/x-y.git

</code>```

git url above has a : in it.  Consequently, when I try to split, I get the following error:

ValueError: dictionary update sequence element #2 has length 4; 2 is required

```<code>dict(item.split(":") for item in data.splitlines())
</code>```

```<code>dict(map(lambda x: x.split(':'), x.splitlines()))
</code>```

expected result:

```<code>{"version" : 67 , " Build Number" : "123master", "Project Name": "xyz", "Git Url" : "origin/master", "Git Branch": "0223445as5njn34nfk6kg", "perforce_url":
  "//project//url//", "artifacts" : " "./": "./" "}

</code>```

Actual result:

```<code>ValueError: dictionary update sequence element #2 has length 4; 2 is required
</code>```

答:
You could write your own parser (yaml like):

```<code>from parsimonious.grammar import Grammar
from parsimonious.nodes import NodeVisitor

data = """
Version: 67
Build Number: 123master
Project Name: git+ssh://git@stash.xyz.com:1999/ns/x-y.git
Git Url: origin/master
Git Branch: 0223445as5njn34nfk6kg
perforce_url:
  //project//url//
artifacts:
  "./": "./"
exclude:
  - manifest.yml
  - node_modules
  - RPMS
  - .git
  - build-toolbox

"""

grammar = Grammar(
    r"""
    entries     = (item / list / ws)+

    item        = key equal ws* (!listsep value) newline?

    list        = listkey listitem+
    listkey     = key equal hs* newline
    listitem    = hs* listsep hs* value newline?

    key         = ~"^[^:]+"m
    equal       = ":"
    listsep     = "-"
    value       = ~".+"

    ws          = (hs / newline)+
    newline     = ~"[\r\n]"
    hs          = ~"[\t ]+"
    """
)

tree = grammar.parse(data)

class YAMLVisitor(NodeVisitor):
    def generic_visit(self, node, visited_children):
        return visited_children or node

    def visit_key(self, node, visited_children):
        return node.text.strip()

    def visit_value(self, node, visited_children):
        return node.text.strip()

    def visit_listkey(self, node, visited_children):
        key, *_ = visited_children
        return key

    def visit_listitem(self, node, visited_children):
        *_, value, _ = visited_children
        return value

    def visit_list(self, node, visited_children):
        key, values = visited_children
        return (key, values)

    def visit_item(self, node, visited_children):
        key, *_, lst, nl = visited_children
        value = lst[1]
        return (key, value)

    def visit_entries(self, node, visited_children):
        output = dict([child[0] for child in visited_children if isinstance(child[0], tuple)])
        return output

yaml = YAMLVisitor()
output = yaml.visit(tree)
print(output)
</code>```

This would yield

```<code>{'Version': '67', 'Build Number': '123master', 'Project Name': 'git+ssh://git@stash.xyz.com:1999/ns/x-y.git', 'Git Url': 'origin/master', 'Git Branch': '0223445as5njn34nfk6kg', 'perforce_url': '//project//url//', 'artifacts': '"./": "./"', 'exclude': ['manifest.yml', 'node_modules', 'RPMS', '.git', 'build-toolbox']}
</code>```

Body:
I want to convert the below unicode in python to a dictionary:

Version: 67
Build Number: 123master
Project Name: git+ssh://git@stash.xyz.com:1999/ns/x-y.git
Git Url: origin/master
Git Branch: 0223445as5njn34nfk6kg
perforce_url:
  //project//url//
artifacts:
  "./": "./"
exclude:
  - manifest.yml
  - node_modules
  - RPMS
  - .git
  - build-toolbox

>>> x
' Version: 67\nBuild Number: 123master\nProject Name: git+ssh://git@stash.xyz.com:1999/ns/x-y.git\nGit Url: origin/master\nGit Branch: 0223445as5njn34nfk6kg\nperforce_url:\n  //project//url//\nartifacts:\n  "./": "./"\nexclude:\n  - manifest.yml\n  - node_modules\n  - RPMS\n  - .git\n  - build-toolbox '
>>>
>>>
>>> dict(map(lambda x: x.split(':'), x.splitlines()))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #2 has length 4; 2 is required

dict(item.split(":") for item in x.splitlines())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #2 has length 4; 2 is required

I believe the problem is with the following item

Project Name: git+ssh://git@stash.xyz.com:1999/ns/x-y.git

git url above has a : in it.  Consequently, when I try to split, I get the following error:

ValueError: dictionary update sequence element #2 has length 4; 2 is required

dict(item.split(":") for item in data.splitlines())

dict(map(lambda x: x.split(':'), x.splitlines()))

expected result:

{"version" : 67 , " Build Number" : "123master", "Project Name": "xyz", "Git Url" : "origin/master", "Git Branch": "0223445as5njn34nfk6kg", "perforce_url":
  "//project//url//", "artifacts" : " "./": "./" "}

Actual result:

ValueError: dictionary update sequence element #2 has length 4; 2 is required

Body:
You could write your own parser (yaml like):

from parsimonious.grammar import Grammar
from parsimonious.nodes import NodeVisitor

data = """
Version: 67
Build Number: 123master
Project Name: git+ssh://git@stash.xyz.com:1999/ns/x-y.git
Git Url: origin/master
Git Branch: 0223445as5njn34nfk6kg
perforce_url:
  //project//url//
artifacts:
  "./": "./"
exclude:
  - manifest.yml
  - node_modules
  - RPMS
  - .git
  - build-toolbox

"""

grammar = Grammar(
    r"""
    entries     = (item / list / ws)+

    item        = key equal ws* (!listsep value) newline?

    list        = listkey listitem+
    listkey     = key equal hs* newline
    listitem    = hs* listsep hs* value newline?

    key         = ~"^[^:]+"m
    equal       = ":"
    listsep     = "-"
    value       = ~".+"

    ws          = (hs / newline)+
    newline     = ~"[\r\n]"
    hs          = ~"[\t ]+"
    """
)

tree = grammar.parse(data)

class YAMLVisitor(NodeVisitor):
    def generic_visit(self, node, visited_children):
        return visited_children or node

    def visit_key(self, node, visited_children):
        return node.text.strip()

    def visit_value(self, node, visited_children):
        return node.text.strip()

    def visit_listkey(self, node, visited_children):
        key, *_ = visited_children
        return key

    def visit_listitem(self, node, visited_children):
        *_, value, _ = visited_children
        return value

    def visit_list(self, node, visited_children):
        key, values = visited_children
        return (key, values)

    def visit_item(self, node, visited_children):
        key, *_, lst, nl = visited_children
        value = lst[1]
        return (key, value)

    def visit_entries(self, node, visited_children):
        output = dict([child[0] for child in visited_children if isinstance(child[0], tuple)])
        return output

yaml = YAMLVisitor()
output = yaml.visit(tree)
print(output)

This would yield

{'Version': '67', 'Build Number': '123master', 'Project Name': 'git+ssh://git@stash.xyz.com:1999/ns/x-y.git', 'Git Url': 'origin/master', 'Git Branch': '0223445as5njn34nfk6kg', 'perforce_url': '//project//url//', 'artifacts': '"./": "./"', 'exclude': ['manifest.yml', 'node_modules', 'RPMS', '.git', 'build-toolbox']}


问:
Making a div inside a div responsive
I am beginner in web development, and i am trying to develop a responsive website. While developing i made one div element that has an image, then inside that i have one box with content "BUILD THAT MATTERS", which is inside a div with a class "firstBlock", the div "firstBlock" moves down when i click the hover button of navigation bar, but the box inside "BUILD THAT MATTERS", doesn't move.

I tried to make the image as a background image of the the div firstBlock, but that made the fitting of image in such a way that it got cropped, so is there any way so that the box inside the div moves with the navigation bar drop down menu, as of now only the firstBlock, that is the image moves, but inner box "BUILD THAT MATTERS" remains fixed in its position.

```<code><-- html-->
<div id="firstBlock">
    <img id="img1" src="image1.jpg">
    <div class="box1">
       <h1 class="text1">BUILD THAT MATTERS</h1>
    </div>
</div>

/*CSS*/
#firstBlock {
    display: flex;
    height: 90%;
    width: 100%;
}
#img1 {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
.box1 {
    display: flex;
    border: 5px solid black;
    position: absolute;
    top: 70%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
}
</code>```

So, the box with content "BUILD THAT MATTERS" should move down with the first block when navigation drop down scrolls down.

fiddle link: https://jsfiddle.net/gj7v8huc/

git link: https://ayush-flash.github.io/StartupLandingPage/StartUpLandingPage/

答:
It is all about parent and child element for using position:absolute. Parent element should have relative position so that the absolute child element will do the calculation of top and left from its expected parent. So apply position:relative to your firstBlock div.

```<code> #firstBlock {
   display: flex;
   height: 90%;
   width: 100%;
   position:relative;
 }
</code>```

Also change your box1 div top and left position as per your parent alignment. I have applied 50% like below.

```<code> .box1 {
    display: flex;
    border: 5px solid black;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
 }
</code>```

As I have already posted in the comment, below is the JSFiddle link.

DEMO

Title: Making a div inside a div responsive

Body:
I am beginner in web development, and i am trying to develop a responsive website. While developing i made one div element that has an image, then inside that i have one box with content "BUILD THAT MATTERS", which is inside a div with a class "firstBlock", the div "firstBlock" moves down when i click the hover button of navigation bar, but the box inside "BUILD THAT MATTERS", doesn't move.

I tried to make the image as a background image of the the div firstBlock, but that made the fitting of image in such a way that it got cropped, so is there any way so that the box inside the div moves with the navigation bar drop down menu, as of now only the firstBlock, that is the image moves, but inner box "BUILD THAT MATTERS" remains fixed in its position.

<-- html-->

BUILD THAT MATTERS

/*CSS*/
#firstBlock {
    display: flex;
    height: 90%;
    width: 100%;
}
#img1 {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
.box1 {
    display: flex;
    border: 5px solid black;
    position: absolute;
    top: 70%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
}

So, the box with content "BUILD THAT MATTERS" should move down with the first block when navigation drop down scrolls down.

fiddle link: https://jsfiddle.net/gj7v8huc/

git link: https://ayush-flash.github.io/StartupLandingPage/StartUpLandingPage/

Body:
It is all about parent and child element for using position:absolute. Parent element should have relative position so that the absolute child element will do the calculation of top and left from its expected parent. So apply position:relative to your firstBlock div.

 #firstBlock {
   display: flex;
   height: 90%;
   width: 100%;
   position:relative;
 }

Also change your box1 div top and left position as per your parent alignment. I have applied 50% like below.

 .box1 {
    display: flex;
    border: 5px solid black;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
 }

As I have already posted in the comment, below is the JSFiddle link.

DEMO


问:
When there is an input box with validation in Angular, it requires two clicks to transfer control to radio button
I have an input box and a radio box. When I click on the input box and then click on the radio box, I suppose the control should transfer to the radio box immediately. Instead, the first time, it shows the error message and the second time, it transfers the control to the radio box.

You can find a plunker of the issue here: No transfer of control to the radio box except after the second click

答:
Yes, that's because you're showing the error as a block, this shifting the radio button.

To image that, imagine that the error pops when the mouse button goes down, while the radio box is checked when the mouse button goes up.

It might be a split second, but it's enough for your user to be fooled.

I would recommend either displaying your error in another way / Findign another layout for your form, or just validate the form on submit.

To validate the form on submit, Use the second parameter of the FormBuilder.group call :

```<code>this.myForm = fb.group({...}, { updateOn: 'submit' });
</code>```

Here is an example of a working form, because the error is blurred out instead of removed (hidden vs style.opacity) : https://next.plnkr.co/edit/QEEviTpocGJ7QHus?open=lib%2Fapp.ts&deferRun=1

Body:
Yes, that's because you're showing the error as a block, this shifting the radio button.

To image that, imagine that the error pops when the mouse button goes down, while the radio box is checked when the mouse button goes up.

It might be a split second, but it's enough for your user to be fooled.

I would recommend either displaying your error in another way / Findign another layout for your form, or just validate the form on submit.

To validate the form on submit, Use the second parameter of the FormBuilder.group call :

this.myForm = fb.group({...}, { updateOn: 'submit' });

Here is an example of a working form, because the error is blurred out instead of removed (hidden vs style.opacity) : https://next.plnkr.co/edit/QEEviTpocGJ7QHus?open=lib%2Fapp.ts&deferRun=1


问:
Type mismatch.Required: MutableList<out ExpandableGroup<Parcelable>>
I'm trying to do expandale recyclerview and I use thoughtbot/expandable-recycler-view, but I've problem with adapter. Maybe someone had similar problem and can help me to solve this problem

1) code of my Parent Class

```<code>/****** parent ******/
class Item(title: String?, items: MutableList<ItemDetail>?) :
ExpandableGroup<ItemDetail>(title, items)
</code>```

2)Child class (here I used parcelize. but now I use :Parcelable)

```<code> // @Parcelize
 // data class ItemDetail(
 // var i_size: String,
 // var i_qty: Int
 //): Parcelable
 class ItemDetail (val i_size: String, val i_qty: Int): Parcelable{
    constructor(parcel: Parcel):this(
     parcel.readString(),
     parcel.readInt()){

   }

   override fun writeToParcel(parcel: Parcel, flags: Int) {
      parcel.writeString(i_size)
      parcel.writeInt(i_qty)
   }

   override fun describeContents(): Int {
     return 0
    }

  companion object CREATOR : Parcelable.Creator<ItemDetail> {
     override fun createFromParcel(parcel: Parcel): ItemDetail {
       return ItemDetail(parcel)
     }

     override fun newArray(size: Int): Array<ItemDetail?> {
      return arrayOfNulls(size)
     }
 }
 }
</code>```

3) Fragment - Adapter

```<code>

    /**** fragment ****/
    val groups: MutableList<Item> = ArrayList<Item>()

    val childs : MutableList<ItemDetail> = ArrayList<ItemDetail>()
    childs.add(ItemDetail("200x200",4))
    childs.add(ItemDetail("300x300",6))
    childs.add(ItemDetail("400x300",2))
    groups.add(Item("Item ISFAKHAN",childs))

    val childs2 : MutableList<ItemDetail> = ArrayList<ItemDetail>()
    childs2.add(ItemDetail("200x200",42))
    childs2.add(ItemDetail("300x300",62))
    childs2.add(ItemDetail("400x300",22))
    groups.add(Item("Item DASTAN",childs2))
    /***  error ***/
    cAdapter = CartAdapter(groups)
    /*** Type mismatch.Required: MutableList<out ExpandableGroup<Parcelable>>? Found: MutableList<Item> ***/

      /****** adapter *****/
    class CartAdapter(groups: MutableList<out ExpandableGroup<Parcelable>>?) :
    ExpandableRecyclerViewAdapter<ItemVH, ItemDetailVH>(groups) {

}
</code>```

答: I believe that your Item class should also be parcelable.

Body:
I'm trying to do expandale recyclerview and I use thoughtbot/expandable-recycler-view, but I've problem with adapter. Maybe someone had similar problem and can help me to solve this problem

1) code of my Parent Class

/****** parent ******/
class Item(title: String?, items: MutableList<ItemDetail>?) :
ExpandableGroup<ItemDetail>(title, items)

2)Child class (here I used parcelize. but now I use :Parcelable)

 // @Parcelize
 // data class ItemDetail(
 // var i_size: String,
 // var i_qty: Int
 //): Parcelable
 class ItemDetail (val i_size: String, val i_qty: Int): Parcelable{
    constructor(parcel: Parcel):this(
     parcel.readString(),
     parcel.readInt()){

   }

   override fun writeToParcel(parcel: Parcel, flags: Int) {
      parcel.writeString(i_size)
      parcel.writeInt(i_qty)
   }

   override fun describeContents(): Int {
     return 0
    }

  companion object CREATOR : Parcelable.Creator<ItemDetail> {
     override fun createFromParcel(parcel: Parcel): ItemDetail {
       return ItemDetail(parcel)
     }

     override fun newArray(size: Int): Array<ItemDetail?> {
      return arrayOfNulls(size)
     }
 }
 }

3) Fragment - Adapter

    /**** fragment ****/
    val groups: MutableList<Item> = ArrayList<Item>()

    val childs : MutableList<ItemDetail> = ArrayList<ItemDetail>()
    childs.add(ItemDetail("200x200",4))
    childs.add(ItemDetail("300x300",6))
    childs.add(ItemDetail("400x300",2))
    groups.add(Item("Item ISFAKHAN",childs))

    val childs2 : MutableList<ItemDetail> = ArrayList<ItemDetail>()
    childs2.add(ItemDetail("200x200",42))
    childs2.add(ItemDetail("300x300",62))
    childs2.add(ItemDetail("400x300",22))
    groups.add(Item("Item DASTAN",childs2))
    /***  error ***/
    cAdapter = CartAdapter(groups)
    /*** Type mismatch.Required: MutableList<out ExpandableGroup<Parcelable>>? Found: MutableList<Item> ***/

      /****** adapter *****/
    class CartAdapter(groups: MutableList<out ExpandableGroup<Parcelable>>?) :
    ExpandableRecyclerViewAdapter<ItemVH, ItemDetailVH>(groups) {

}


问:
unable to import large database to docker mysql container
I'm trying to import a large database to a mysql container. I've mounted host directories as volumes for the mysql container. So the data is persistent on host. The importing sql file is 14 GB+. The mysql container becomes unresponsive half way of through importing. When I run docker stats I can see the CPU % usage becomes < 1 once mysql container ate all the memory available. I tried increasing memory of docker up to 10 GB and It creates more tables from import when I allocate more memory to Docker. But I cannot allocate more than 10GB from host.

Following is my docker-compose.yml file

```<code>mysql:
    image: mysql:5.6
    environment:
        - MYSQL_ROOT_PASSWORD=12345678
    volumes:
        - ./mysql/lib:/var/lib/mysql
        - ./mysql/conf.d:/etc/mysql/conf.d
        - ./mysql/log:/var/log/mysql
        - /tmp:/tmp
    ports:
        - "3306:3306"
</code>```

I'm using Docker for mac which has docker version 1.12.1

I was using docker exec -it docker_mysql_1 /bin/bash to login to container and import the sql file from /tmp

Also I tried the way recommended by mysql repo by mounting sql file to /docker-entrypoint-initdb.d. But that also halt the mysql init.

UPDATE 1

```<code>$ docker info
Containers: 1
 Running: 0
 Paused: 0
 Stopped: 1
Images: 2
Server Version: 1.12.1
Storage Driver: aufs
 Root Dir: /var/lib/docker/aufs
 Backing Filesystem: extfs
 Dirs: 18
 Dirperm1 Supported: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: host bridge null overlay
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Security Options: seccomp
Kernel Version: 4.4.20-moby
Operating System: Alpine Linux v3.4
OSType: linux
Architecture: x86_64
CPUs: 4
Total Memory: 9.744 GiB
Name: moby
ID: 43S4:LA5E:6MTG:IFOG:HHJC:HYLX:LYIT:YU43:QGBQ:K5I5:Z6LP:AENZ
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): true
 File Descriptors: 16
 Goroutines: 27
 System Time: 2016-10-12T07:52:58.516469676Z
 EventsListeners: 1
No Proxy: *.local, 169.254/16
Registry: https://index.docker.io/v1/
Insecure Registries:
 127.0.0.0/8

$ df -h
Filesystem      Size   Used  Avail Capacity iused      ifree %iused  Mounted on
/dev/disk1     233Gi  141Gi   92Gi    61% 2181510 4292785769    0%   /
devfs          193Ki  193Ki    0Bi   100%     668          0  100%   /dev
map -hosts       0Bi    0Bi    0Bi   100%       0          0  100%   /net
map auto_home    0Bi    0Bi    0Bi   100%       0          0  100%   /home
/dev/disk2s2   466Gi   64Gi  401Gi    14%    1857 4294965422    0%   /Volumes/mac
/dev/disk2s3   465Gi   29Gi  436Gi     7%  236633    3575589    6%   /Volumes/PORTABLE
/dev/disk3s1   100Mi   86Mi   14Mi    86%      12 4294967267    0%   /Volumes/Vagrant
</code>```

I was using /dev/disk1 directories to mount volumes.

答:
Even I had run into similar problem.
Follow the below process, this might help you:
Firstly copy your sql file(filename.sql) into the db container.

```<code>docker cp filename.sql docker_db_container:/filename.sql
</code>```

Later login to your db container,and populate db with this(filename.sql) file.
In order to insert your file(filename.sql) in the database,
Go-to mysql into the db container, use the db in which you want to store the database,ie. use database_name;

```<code>source /filename.sql
</code>```

Yet if you're facing issue wrt to large packet size,then increase containers packet size

```<code>docker exec -it docker_db_container bash -c "echo 'max_allowed_packet = 1024M' >> /etc/mysql/mysql.conf.d/mysqld.cnf"
</code>```

Body:
I'm trying to import a large database to a mysql container. I've mounted host directories as volumes for the mysql container. So the data is persistent on host. The importing sql file is 14 GB+. The mysql container becomes unresponsive half way of through importing. When I run docker stats I can see the CPU % usage becomes < 1 once mysql container ate all the memory available. I tried increasing memory of docker up to 10 GB and It creates more tables from import when I allocate more memory to Docker. But I cannot allocate more than 10GB from host.

Following is my docker-compose.yml file

mysql:
    image: mysql:5.6
    environment:
        - MYSQL_ROOT_PASSWORD=12345678
    volumes:
        - ./mysql/lib:/var/lib/mysql
        - ./mysql/conf.d:/etc/mysql/conf.d
        - ./mysql/log:/var/log/mysql
        - /tmp:/tmp
    ports:
        - "3306:3306"

I'm using Docker for mac which has docker version 1.12.1

I was using docker exec -it docker_mysql_1 /bin/bash to login to container and import the sql file from /tmp

Also I tried the way recommended by mysql repo by mounting sql file to /docker-entrypoint-initdb.d. But that also halt the mysql init.

UPDATE 1

$ docker info
Containers: 1
 Running: 0
 Paused: 0
 Stopped: 1
Images: 2
Server Version: 1.12.1
Storage Driver: aufs
 Root Dir: /var/lib/docker/aufs
 Backing Filesystem: extfs
 Dirs: 18
 Dirperm1 Supported: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: host bridge null overlay
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Security Options: seccomp
Kernel Version: 4.4.20-moby
Operating System: Alpine Linux v3.4
OSType: linux
Architecture: x86_64
CPUs: 4
Total Memory: 9.744 GiB
Name: moby
ID: 43S4:LA5E:6MTG:IFOG:HHJC:HYLX:LYIT:YU43:QGBQ:K5I5:Z6LP:AENZ
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): true
 File Descriptors: 16
 Goroutines: 27
 System Time: 2016-10-12T07:52:58.516469676Z
 EventsListeners: 1
No Proxy: *.local, 169.254/16
Registry: https://index.docker.io/v1/
Insecure Registries:
 127.0.0.0/8

$ df -h
Filesystem      Size   Used  Avail Capacity iused      ifree %iused  Mounted on
/dev/disk1     233Gi  141Gi   92Gi    61% 2181510 4292785769    0%   /
devfs          193Ki  193Ki    0Bi   100%     668          0  100%   /dev
map -hosts       0Bi    0Bi    0Bi   100%       0          0  100%   /net
map auto_home    0Bi    0Bi    0Bi   100%       0          0  100%   /home
/dev/disk2s2   466Gi   64Gi  401Gi    14%    1857 4294965422    0%   /Volumes/mac
/dev/disk2s3   465Gi   29Gi  436Gi     7%  236633    3575589    6%   /Volumes/PORTABLE
/dev/disk3s1   100Mi   86Mi   14Mi    86%      12 4294967267    0%   /Volumes/Vagrant

I was using /dev/disk1 directories to mount volumes.

Body:
Even I had run into similar problem.
Follow the below process, this might help you:
Firstly copy your sql file(filename.sql) into the db container.

docker cp filename.sql docker_db_container:/filename.sql

Later login to your db container,and populate db with this(filename.sql) file.
In order to insert your file(filename.sql) in the database,
Go-to mysql into the db container, use the db in which you want to store the database,ie. use database_name;

source /filename.sql

Yet if you're facing issue wrt to large packet size,then increase containers packet size

docker exec -it docker_db_container bash -c "echo 'max_allowed_packet = 1024M' >> /etc/mysql/mysql.conf.d/mysqld.cnf"


问:
Is console.log asynchronous?
I had an incident in my Angular 6 application the other day involving some code that looked like this:

```<code>console.log('before:', value);
this.changeValue(value);
console.log('after:', value);
</code>```

changeValue() modifies value in some way. I expected to see the unmodified value in the console before the call to changeValue() then the modified value after. Instead I saw the modified value before and after.

I guess it proved that my changeValue() function worked, but it also indicated to me that console.log() is asynchronous--that is, it doesn't print out the value to the console right away; it waits for a bit... and when it finally does print the value, it's the value as it is at that moment. In other words, the first call to console.log() above waited until after the call to changeValue() before printing, and when it did, the value had already changed.

So am I correct in inferring that console.log() is asynchronous. If so, why is that? It causes a lot of confusion when debugging.

答:
No, console.log() is synchronous. It's actually your changeValue() function that doesn't work the way you think.

First, JavaScript doesn't pass variables by reference, but by pointer to object (as do many other languages). So although the variable value inside your function and the variable value in the outer scope both hold the same object, they are still separate variables. Mutatin the object affects both variables, but direct assignments to one variable do not affect the other. For example, this obviously wouldn't work:

```<code>function changeValue(x) { x = 123; }
</code>```

Second, in JavaScript the shorthand assignment a += b does not mutate the existing object stored in a. Instead it works exactly like a = a + b and assigns a new object to the variable. As mentioned above, this only affects the variable inside the function, but doesn't affect the one outside, so your changes are lost after the function returns.

More examples:

```<code>function willwork(obj) { obj.foo = "bar"; }
function willwork(obj) { obj["foo"] = 1234; }
function willwork(obj) { obj.push("foo"); }

function wontwork(obj) { obj = "foo"; }
function wontwork(obj) { obj += 123; }
function wontwork(obj) { obj = obj + 123; }
</code>```

OwnerDisplayName: Gibran Shah

Title: Is console.log asynchronous?

Body:
I had an incident in my Angular 6 application the other day involving some code that looked like this:

console.log('before:', value);
this.changeValue(value);
console.log('after:', value);

changeValue() modifies value in some way. I expected to see the unmodified value in the console before the call to changeValue() then the modified value after. Instead I saw the modified value before and after.

I guess it proved that my changeValue() function worked, but it also indicated to me that console.log() is asynchronous--that is, it doesn't print out the value to the console right away; it waits for a bit... and when it finally does print the value, it's the value as it is at that moment. In other words, the first call to console.log() above waited until after the call to changeValue() before printing, and when it did, the value had already changed.

So am I correct in inferring that console.log() is asynchronous. If so, why is that? It causes a lot of confusion when debugging.

Body:
No, console.log() is synchronous. It's actually your changeValue() function that doesn't work the way you think.

First, JavaScript doesn't pass variables by reference, but by pointer to object (as do many other languages). So although the variable value inside your function and the variable value in the outer scope both hold the same object, they are still separate variables. Mutatin the object affects both variables, but direct assignments to one variable do not affect the other. For example, this obviously wouldn't work:

function changeValue(x) { x = 123; }

Second, in JavaScript the shorthand assignment a += b does not mutate the existing object stored in a. Instead it works exactly like a = a + b and assigns a new object to the variable. As mentioned above, this only affects the variable inside the function, but doesn't affect the one outside, so your changes are lost after the function returns.

More examples:

function willwork(obj) { obj.foo = "bar"; }
function willwork(obj) { obj["foo"] = 1234; }
function willwork(obj) { obj.push("foo"); }

function wontwork(obj) { obj = "foo"; }
function wontwork(obj) { obj += 123; }
function wontwork(obj) { obj = obj + 123; }


Title: Pytorch : Results of vector multiplications are different for same input

Body:
I did not understand why these multiplication outputs are different.

print(features*weights)
print('------------')
print(features*weights.view(5,1))
print('------------')
print(torch.mm(features,weights.view(5,1)))

outputs:

tensor([[ 0.1314, -0.2796,  1.1668, -0.1540, -2.8442]])
------------
tensor([[ 0.1314, -0.7035, -0.8472,  0.9971, -1.5130],
        [ 0.0522, -0.2796, -0.3367,  0.3963, -0.6013],
        [-0.1809,  0.9688,  1.1668, -1.3733,  2.0837],
        [-0.0203,  0.1086,  0.1308, -0.1540,  0.2336],
        [ 0.2469, -1.3224, -1.5927,  1.8745, -2.8442]])
------------
tensor([[-1.9796]])

Body:
If I'm not wrong, what you are trying to understand is:

features = torch.rand(1, 5)
weights = torch.Tensor([1, 2, 3, 4, 5])
print(features)
print(weights)

# Element-wise multiplication of shape (1 x 5)
# out = [f1*w1, f2*w2, f3*w3, f4*w4, f5*w5]
print(features*weights)

# weights has been reshaped to (5, 1)
# Element-wise multiplication of shape (5 x 5)
# out =   [f1*w1, f2*w1, f3*w1, f4*w1, f5*w1]
#         [f1*w2, f2*w2, f3*w2, f4*w2, f5*w2]
#         [f1*w3, f2*w3, f3*w3, f4*w3, f5*w3]
#         [f1*w4, f2*w4, f3*w4, f4*w4, f5*w4]
#         [f1*w5, f2*w5, f3*w5, f4*w5, f5*w5]
print(features*weights.view(5, 1))

# Matrix-multiplication
# (1, 5) * (5, 1) -> (1, 1)
# out = [f1*w1 + f2*w2 + f3*w3 + f4*w4 + f5*w5]
print(torch.mm(features, weights.view(5, 1)))

Output:

tensor([[0.1467, 0.6925, 0.0987, 0.5244, 0.6491]])  # features
tensor([1., 2., 3., 4., 5.])                        # weights

tensor([[0.1467, 1.3851, 0.2961, 2.0976, 3.2455]])  # features*weights
tensor([[0.1467, 0.6925, 0.0987, 0.5244, 0.6491],
        [0.2934, 1.3851, 0.1974, 1.0488, 1.2982],
        [0.4400, 2.0776, 0.2961, 1.5732, 1.9473],
        [0.5867, 2.7701, 0.3947, 2.0976, 2.5964],
        [0.7334, 3.4627, 0.4934, 2.6220, 3.2455]])  # features*weights.view(5,1)
tensor([[7.1709]])                                  # torch.mm(features, weights.view(5, 1))


问:
How to send a file from my app to another many application which do support sharing data
I'm actually trying to send a data which is coming from an API(as a text not as a file) to me and I want to send that data as a text file by many apps which includes sharing of files like WhatsApp, hike, telegram, shareit, etc.</p>

答:
-Can you try this code and see if it is working with you:</p>

```<code>Intent shareIntent = new Intent("android.intent.action.SEND");
shareIntent.setType("text/plain");
shareIntent.putExtra("android.intent.extra.SUBJECT",
                     "Codes Easy");
shareIntent.putExtra("android.intent.extra.SUBJECT",
         "Add a text to be shared here");
startActivity(Intent.createChooser(shareIntent, "Share with"));
</code>```

Body:
-Can you try this code and see if it is working with you:

Intent shareIntent = new Intent("android.intent.action.SEND");
shareIntent.setType("text/plain");
shareIntent.putExtra("android.intent.extra.SUBJECT",
                     "Codes Easy");
shareIntent.putExtra("android.intent.extra.SUBJECT",
         "Add a text to be shared here");
startActivity(Intent.createChooser(shareIntent, "Share with"));


问:
How to invoke lambda when lex does not process the intent automatically?
My Lex bot has four intents. Suppose a user asks a question at the very beginning of the conversation and this question is not allotted to any of the four intents. Hence no intent will be established. When this happens, I want to call lambda to run an "intent suggestion model" (built using topic modeling) to suggest the user about what the intent of the question might be. Also, lambda will have to store such queries in a database (s3 or RDB) so that if such queries are repetitive, then that intent can eventually be added to the bot and for other analytical solutions.</p>

答:
What you need is a fallback intent but Lex does not support fallback intents as of now.

You can still achieve this if you use a bridge between your chat client and Lex.

Setup an API Gateway and Lambda function in between your chat-client and the Lex.

Your chat-client will send a request to API Gateway, API Gateway will forward this to Lambda function which will be used to call Lex and get response from it. Lex will have one more lambda function as a webhook.

In the Lambda function you used to call Lex, we can check if any intent was matched or we got an error message, if it's an error message and trigger some action like intent suggestion model.

You need to use boto library to call Lex and use post_text() method.

Hope it helps.


问:
Why do I get this error inserting a character into a MATLAB matrix?
I am constructing a 16x16 matrix, consisting of just letters in MATLAB. I tried for example:

```<code>for i=1:2:3
    C(i,2)=char('B');
end
</code>```

to place the letter 'B' in its corresponding place in the matrix. However this gives a value of 66 in the matrix instead of just the letter 'B'. What is going wrong?

答:
The problem is most likely that you already have a variable called C that contains numeric data in it. When you try to place a character into a numeric matrix, the character gets converted to its ASCII value. If you clear the variable C before running your above code, you should get a character matrix for C:

```<code>>> clear C
>> for i=1:2:3, C(i,2) = 'B'; end
>> C

C =

 B

 B
</code>```

Note in this case that C is a 3-by-2 array with null characters (ASCII code 0) in the first column and second row of the second column. If you want to initialize C to be a 16-by-16 character array of null characters, you can replace the CLEAR statement in the above code with:

```<code>C = char(zeros(16));
</code>```

And then run your loop to fill in your values. Also note that char('B') is redundant, since 'B' is already of type character.

Body:
I am constructing a 16x16 matrix, consisting of just letters in MATLAB. I tried for example:

for i=1:2:3
    C(i,2)=char('B');
end

to place the letter 'B' in its corresponding place in the matrix. However this gives a value of 66 in the matrix instead of just the letter 'B'. What is going wrong?

Body:
The problem is most likely that you already have a variable called C that contains numeric data in it. When you try to place a character into a numeric matrix, the character gets converted to its ASCII value. If you clear the variable C before running your above code, you should get a character matrix for C:

>> clear C
>> for i=1:2:3, C(i,2) = 'B'; end
>> C

C =

 B

 B

Note in this case that C is a 3-by-2 array with null characters (ASCII code 0) in the first column and second row of the second column. If you want to initialize C to be a 16-by-16 character array of null characters, you can replace the CLEAR statement in the above code with:

C = char(zeros(16));

And then run your loop to fill in your values. Also note that char('B') is redundant, since 'B' is already of type character.


问:
Changing Notification RemoteViews Background Color
I've a problem changing my Background-Color with the Application-Theme.

```<code>NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this);

TypedValue typedValue = new TypedValue();

getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);

int iPrimaryColor = typedValue.data;

getTheme().resolveAttribute(R.attr.colorPrimaryDark, typedValue, true);

int iPrimaryDarkColor = typedValue.data;

Intent notIntent = new Intent(getApplicationContext(), MainActivity.class);
notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

PendingIntent notOpenOnClick = PendingIntent.getActivity(getApplicationContext(), 0, notIntent, PendingIntent.FLAG_UPDATE_CURRENT);

RemoteViews smallContentView = new RemoteViews(getPackageName(), R.layout.notification_small);
RemoteViews bigContentView = new RemoteViews(getPackageName(), R.layout.notification_expanded);

nBuilder.setSmallIcon(R.drawable.not_icon)
    .setOngoing(true)
    .setContentTitle(getCurrentSong().getTitle())
    .setContentIntent(notOpenOnClick);

Notification not = nBuilder.build();

smallContentView.setInt(R.id.not_linLayout, "setBackgroundColor", iPrimaryColor);
smallContentView.setInt(R.id.not_imvDivider, "setBackgroundColor", iPrimaryDarkColor);

bigContentView.setInt(R.id.not_linLayout, "setBackgroundColor", iPrimaryColor);
bigContentView.setInt(R.id.not_imvDivider, "setBackgroundColor", iPrimaryDarkColor);

setListeners(smallContentView);
setListeners(bigContentView);

not.contentView = smallContentView;
not.bigContentView = bigContentView;

if (isPlaying()) {
    not.contentView.setImageViewResource(R.id.not_btnPlayPause, R.drawable.ic_pause_48dp);
    not.bigContentView.setImageViewResource(R.id.not_btnPlayPause, R.drawable.ic_pause_48dp);
}
else {
    not.contentView.setImageViewResource(R.id.not_btnPlayPause, R.drawable.ic_play_48dp);
    not.bigContentView.setImageViewResource(R.id.not_btnPlayPause, R.drawable.ic_play_48dp);
}
</code>```

I already tried this, but the Background of my Notification is still white.
The ID's are correct, the View linLayout is a LinearLayout.

Please keep in mind: The whole codes is invoked in a Service!

Thanks!

答:
the setColorized documentation says:

Set whether this notification should be colorized. When set, the color set with setColor(int) will be used as the background color of this notification.

This should only be used for high priority ongoing tasks like navigation, an ongoing call, or other similarly high-priority events for the user.

For most styles, the coloring will only be applied if the notification is for a foreground service notification.

However, for MediaStyle and DecoratedMediaCustomViewStyle notifications that have a media session attached there is no such requirement.

Calling this method on any version prior to O will not have an effect on the notification and it won't be colorized.

Kotlin code:

```<code>import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import androidx.core.app.NotificationCompat
import androidx.media.app.NotificationCompat.DecoratedMediaCustomViewStyle

// create a MediaSession so that we can create a DecoratedMediaCustomViewStyle
val mediaSession = MediaSessionCompat(applicationContext,"tag")
mediaSession.setFlags(0)
mediaSession.setPlaybackState(PlaybackStateCompat.Builder()
        .setState(PlaybackStateCompat.STATE_NONE,0,0f)
        .build())

// create & display the colorized notification
notificationManager.notify(
        0,
        NotificationCompat
                .Builder(this,notificationChannel)
                .setStyle(DecoratedMediaCustomViewStyle()
                        .setMediaSession(mediaSession.sessionToken))
                .setSmallIcon(R.drawable.ic_app_foreground)
                .setColor(getColor(android.R.color.black))
                .setColorized(true)
                .setContentText("Hello, World!")
                .build())

....

// cleanup upon dismissing the notification
mediaSession.release()
</code>```

Body:
I've a problem changing my Background-Color with the Application-Theme.

NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this);

TypedValue typedValue = new TypedValue();

getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);

int iPrimaryColor = typedValue.data;

getTheme().resolveAttribute(R.attr.colorPrimaryDark, typedValue, true);

int iPrimaryDarkColor = typedValue.data;

Intent notIntent = new Intent(getApplicationContext(), MainActivity.class);
notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

PendingIntent notOpenOnClick = PendingIntent.getActivity(getApplicationContext(), 0, notIntent, PendingIntent.FLAG_UPDATE_CURRENT);

RemoteViews smallContentView = new RemoteViews(getPackageName(), R.layout.notification_small);
RemoteViews bigContentView = new RemoteViews(getPackageName(), R.layout.notification_expanded);

nBuilder.setSmallIcon(R.drawable.not_icon)
    .setOngoing(true)
    .setContentTitle(getCurrentSong().getTitle())
    .setContentIntent(notOpenOnClick);

Notification not = nBuilder.build();

smallContentView.setInt(R.id.not_linLayout, "setBackgroundColor", iPrimaryColor);
smallContentView.setInt(R.id.not_imvDivider, "setBackgroundColor", iPrimaryDarkColor);

bigContentView.setInt(R.id.not_linLayout, "setBackgroundColor", iPrimaryColor);
bigContentView.setInt(R.id.not_imvDivider, "setBackgroundColor", iPrimaryDarkColor);

setListeners(smallContentView);
setListeners(bigContentView);

not.contentView = smallContentView;
not.bigContentView = bigContentView;

if (isPlaying()) {
    not.contentView.setImageViewResource(R.id.not_btnPlayPause, R.drawable.ic_pause_48dp);
    not.bigContentView.setImageViewResource(R.id.not_btnPlayPause, R.drawable.ic_pause_48dp);
}
else {
    not.contentView.setImageViewResource(R.id.not_btnPlayPause, R.drawable.ic_play_48dp);
    not.bigContentView.setImageViewResource(R.id.not_btnPlayPause, R.drawable.ic_play_48dp);
}

I already tried this, but the Background of my Notification is still white.
The ID's are correct, the View linLayout is a LinearLayout.

Please keep in mind: The whole codes is invoked in a Service!

Thanks!

Body:
the setColorized documentation says:

Set whether this notification should be colorized. When set, the color set with setColor(int) will be used as the background color of this notification.

This should only be used for high priority ongoing tasks like navigation, an ongoing call, or other similarly high-priority events for the user.

For most styles, the coloring will only be applied if the notification is for a foreground service notification.

However, for MediaStyle and DecoratedMediaCustomViewStyle notifications that have a media session attached there is no such requirement.

Calling this method on any version prior to O will not have an effect on the notification and it won't be colorized.

Kotlin code:

import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import androidx.core.app.NotificationCompat
import androidx.media.app.NotificationCompat.DecoratedMediaCustomViewStyle

// create a MediaSession so that we can create a DecoratedMediaCustomViewStyle
val mediaSession = MediaSessionCompat(applicationContext,"tag")
mediaSession.setFlags(0)
mediaSession.setPlaybackState(PlaybackStateCompat.Builder()
        .setState(PlaybackStateCompat.STATE_NONE,0,0f)
        .build())

// create & display the colorized notification
notificationManager.notify(
        0,
        NotificationCompat
                .Builder(this,notificationChannel)
                .setStyle(DecoratedMediaCustomViewStyle()
                        .setMediaSession(mediaSession.sessionToken))
                .setSmallIcon(R.drawable.ic_app_foreground)
                .setColor(getColor(android.R.color.black))
                .setColorized(true)
                .setContentText("Hello, World!")
                .build())

....

// cleanup upon dismissing the notification
mediaSession.release()


问:
Custom UIButton in Tab Bar not able to be hidden
I have went through many of Stacksoverflow question before asking. None was able to solve my issue. I made a custom button using

```<code>class TabBarViewController: UITabBarController {

let button = UIButton.init(type: .custom)

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

    button.setImage(UIImage(named: "assetIcon"), for: .normal)
    button.backgroundColor = .blue
    button.layer.cornerRadius = 35

    self.view.insertSubview(button, aboveSubview: self.tabBar)
    self.view.layoutIfNeeded()
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    let distance =  ((self.view.bounds.height)/100)*11

    // safe place to set the frame of button manually
    button.frame = CGRect.init(x: self.tabBar.center.x - 32, y: self.view.bounds.height - distance, width: 70, height: 70)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func hideTabButton() {
    self.button.isHidden = true
}

func showTabButton() {
    self.button.isHidden = false
   }
}
</code>```

However, when i called the function of hideTabButton from another view where I want to hide it, the button still shows up.. I called the function from

```<code> override func viewDidAppear(_ animated: Bool) {
    let vc = storyboard?.instantiateViewController(withIdentifier: "tabBarVC") as! TabBarViewController
    vc.hideTabButton()
}
</code>```

It didnt hide the button. Anyone with a solution or guide that can be of help?

答:
You are trying to hide it before it is created you just instantiated TabBarViewController right now you should just pass a flag from current screen to TabBarViewController screen and then in TabBarViewController screen
Do following.

```<code>class TabBarViewController: UITabBarController {
var hideButton:Bool = false
let button = UIButton.init(type: .custom)

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

    button.setImage(UIImage(named: "assetIcon"), for: .normal)
    button.backgroundColor = .blue
    button.layer.cornerRadius = 35
    self.view.insertSubview(button, aboveSubview: self.tabBar)
    self.view.layoutIfNeeded()
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    let distance =  ((self.view.bounds.height)/100)*11

    // safe place to set the frame of button manually
    button.frame = CGRect.init(x: self.tabBar.center.x - 32, y: self.view.bounds.height - distance, width: 70, height: 70)
    button.isHidden = hideButton
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func hideTabButton() {
    self.button.isHidden = true
}

func showTabButton() {
    self.button.isHidden = false
   }
}
</code>```

Now just pass boolean value to TabbarViewController if  not instantiated already

```<code>override func viewDidAppear(_ animated: Bool) {
  let vc = storyboard?.instantiateViewController(withIdentifier: "tabBarVC") as! TabBarViewController
  vc.hideButton=true
}
</code>```

If your tabbar is already instantiated Not instatiate it again just access it like below

```<code>if let tabController = self.tabbarController as? TabbarViewController{ tabController.button.isHidden = true }
</code>```

And When trying unhide it back just change true to false

```<code>if let tabController = self.tabbarController as? TabbarViewController{ tabController.button.isHidden = false }
</code>```

Body:
I have went through many of Stacksoverflow question before asking. None was able to solve my issue. I made a custom button using

class TabBarViewController: UITabBarController {

let button = UIButton.init(type: .custom)

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

    button.setImage(UIImage(named: "assetIcon"), for: .normal)
    button.backgroundColor = .blue
    button.layer.cornerRadius = 35

    self.view.insertSubview(button, aboveSubview: self.tabBar)
    self.view.layoutIfNeeded()
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    let distance =  ((self.view.bounds.height)/100)*11

    // safe place to set the frame of button manually
    button.frame = CGRect.init(x: self.tabBar.center.x - 32, y: self.view.bounds.height - distance, width: 70, height: 70)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func hideTabButton() {
    self.button.isHidden = true
}

func showTabButton() {
    self.button.isHidden = false
   }
}

However, when i called the function of hideTabButton from another view where I want to hide it, the button still shows up.. I called the function from

 override func viewDidAppear(_ animated: Bool) {
    let vc = storyboard?.instantiateViewController(withIdentifier: "tabBarVC") as! TabBarViewController
    vc.hideTabButton()
}

It didnt hide the button. Anyone with a solution or guide that can be of help?

Body:
You are trying to hide it before it is created you just instantiated TabBarViewController right now you should just pass a flag from current screen to TabBarViewController screen and then in TabBarViewController screen
Do following.

class TabBarViewController: UITabBarController {
var hideButton:Bool = false
let button = UIButton.init(type: .custom)

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

    button.setImage(UIImage(named: "assetIcon"), for: .normal)
    button.backgroundColor = .blue
    button.layer.cornerRadius = 35
    self.view.insertSubview(button, aboveSubview: self.tabBar)
    self.view.layoutIfNeeded()
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    let distance =  ((self.view.bounds.height)/100)*11

    // safe place to set the frame of button manually
    button.frame = CGRect.init(x: self.tabBar.center.x - 32, y: self.view.bounds.height - distance, width: 70, height: 70)
    button.isHidden = hideButton
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func hideTabButton() {
    self.button.isHidden = true
}

func showTabButton() {
    self.button.isHidden = false
   }
}

Now just pass boolean value to TabbarViewController if  not instantiated already

override func viewDidAppear(_ animated: Bool) {
  let vc = storyboard?.instantiateViewController(withIdentifier: "tabBarVC") as! TabBarViewController
  vc.hideButton=true
}

If your tabbar is already instantiated Not instatiate it again just access it like below

if let tabController = self.tabbarController as? TabbarViewController{ tabController.button.isHidden = true }

And When trying unhide it back just change true to false

if let tabController = self.tabbarController as? TabbarViewController{ tabController.button.isHidden = false }


问:
Why i am not able to deep copy a class member
Not able to deep copy one class object to another;

I have a geometry Class object

```<code>class Geometry
 {
  public:
     std::string stdstrType;
     bool bValid;

 public:

  Geometry()
    {
       stdstrType = "NO_TYPE";
       bValid = false;

    }

  Geometry( std::string strType , bool bValue )
  {
    stdstrType = strType;
    bValid = bValue;
  }

 Geometry(const Geometry &g)
{
    stdstrType = g.stdstrType;
    bValid = g.bValid;
}

 ~Geometry()
 {
     qDebug() << "Geometry  destructor called";
 }

 virtual void draw();
 bool isValid();
 void setValidState(bool bState);
 virtual void Init();
 std::string GetName();
};
</code>```

I have a Container class

```<code> class Container
  {
   private:
    std::string stdstrContainerName;
    std::string stdstrPluginType;
    Geometry* Geom;

  public:
    Container();
    Container(std::string, std::string, Geometry* geometry = nullptr);
    Container(const  Container& obj);
    ~Container();
    std::string GetName();
    std::string GetType();
    void SetName(std::string stdstrName);
    Geometry* GetGeometry();
    void SetGeometry(Geometry* Geom);

  };

 Container::Container(std::string strName, std::string strType, Geometry*
 geometry) : Geom(geometry)
{
   stdstrContainerName = strName;
  stdstrPluginType = strType;
}

 Container::Container(const Container& obj) {
  stdstrContainerName = obj.stdstrContainerName;
  stdstrPluginType = obj.stdstrPluginType;
  Geom = new Geometry;
  *Geom = *obj.Geom;  // This Line gives error
 }
</code>```

since Container object has a data member with Geometry pointer and the scope of geometry object is shorter than the container object
so i want to do a deep copy geometry object inside the Container object.

This is the line in copy constructor which gives me error

```<code>*Geom = *obj.Geom;  // This Line gives error
</code>```

This is how i Initilize the Container object

```<code> Geometry* geom = new Geometry;
 Container* cont = new Container("Group", "NONE", geom);
</code>```

答:
As commented by @rafix07, you should always check pointer before dereferencing it.

```<code>if(obj.Geom != nullptr) // Check
  *Geom = *obj.Geom;
</code>```

Also along with copy constructor, you should consider defining assignment operator for Geometry class, to achieve your objective of deep copy.

```<code>Geometry & Geometry::operator = (const Geometry &g)
{
  if(this != &g)
  {
    stdstrType = g.stdstrType;
    bValid = g.bValid;
  }
  return *this;
}
</code>```

Body:
Not able to deep copy one class object to another;

I have a geometry Class object

class Geometry
 {
  public:
     std::string stdstrType;
     bool bValid;

 public:

  Geometry()
    {
       stdstrType = "NO_TYPE";
       bValid = false;

    }

  Geometry( std::string strType , bool bValue )
  {
    stdstrType = strType;
    bValid = bValue;
  }

 Geometry(const Geometry &g)
{
    stdstrType = g.stdstrType;
    bValid = g.bValid;
}

 ~Geometry()
 {
     qDebug() << "Geometry  destructor called";
 }

 virtual void draw();
 bool isValid();
 void setValidState(bool bState);
 virtual void Init();
 std::string GetName();
};

I have a Container class

 class Container
  {
   private:
    std::string stdstrContainerName;
    std::string stdstrPluginType;
    Geometry* Geom;

  public:
    Container();
    Container(std::string, std::string, Geometry* geometry = nullptr);
    Container(const  Container& obj);
    ~Container();
    std::string GetName();
    std::string GetType();
    void SetName(std::string stdstrName);
    Geometry* GetGeometry();
    void SetGeometry(Geometry* Geom);

  };

 Container::Container(std::string strName, std::string strType, Geometry*
 geometry) : Geom(geometry)
{
   stdstrContainerName = strName;
  stdstrPluginType = strType;
}

 Container::Container(const Container& obj) {
  stdstrContainerName = obj.stdstrContainerName;
  stdstrPluginType = obj.stdstrPluginType;
  Geom = new Geometry;
  *Geom = *obj.Geom;  // This Line gives error
 }

since Container object has a data member with Geometry pointer and the scope of geometry object is shorter than the container object
so i want to do a deep copy geometry object inside the Container object.

This is the line in copy constructor which gives me error

*Geom = *obj.Geom;  // This Line gives error

This is how i Initilize the Container object

 Geometry* geom = new Geometry;
 Container* cont = new Container("Group", "NONE", geom);

Body:
As commented by @rafix07, you should always check pointer before dereferencing it.

if(obj.Geom != nullptr) // Check
  *Geom = *obj.Geom;

Also along with copy constructor, you should consider defining assignment operator for Geometry class, to achieve your objective of deep copy.

Geometry & Geometry::operator = (const Geometry &g)
{
  if(this != &g)
  {
    stdstrType = g.stdstrType;
    bValid = g.bValid;
  }
  return *this;
}


问:
React: useEffect performance issue on Android app webview?
I am building a web page with React using the useEffect hook api

but when I open the page in the webview of my client's android app, it always take more than 5000ms between first render call and the useEffect call.

here is my code:

import React, { useEffect, useState, useRef } from 'react';
import axios from 'axios';

const api = {
  ins: axios.create({
    baseURL: 'https://new.h5no1.com/apg-great-china-3/api'
  })
};

function App() {
  const [data, setData] = useState();
  const t = useRef(Date.now());
  useEffect(() => {
    console.log(Date.now() - t.current); // 5000+, useLayoutEffect log 30~50 only
    api.ins
      .post('/user/is_on_list', {
        openid: 'xxx',
        openToken: 'xxx'
      })
      .then(res => {
        setData(JSON.stringify(res.data))
      });
  }, []);

  return
{data ? data : 'loading'}
;
}

export default App;

```

<p>and when I change to use the <code>useLayoutEffect</code>, it works fine, the problem is, I don't why using <code>useEffect</code> can cause an issue here while just using it to fetch data from web api ?</p>

<p>the UA string I get from the webview of the app</p>

```Mozilla/5.0 (Linux; Android 9; MI 8 Lite Build/PKQ1.181007.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/72.0.3626.121 Mobile Safari/537.36 PARS/50601
```

I have tested on other android devices with the app, they all behaved the same.

and using componentDidMount works fine, too.

答: useLayoutEffect is synonym for componentDidMount in term of execution. Easiest case looks like this: render => useLayoutEffect(componentDidMount ) => animationFrame => useEffect. It basically means that if you have some blocking execution in rendering or in layout effect then useEffect will be delayed. This is react behaviour not android specific tho.</p>

Body:
I am building a web page with React using the useEffect hook api

but when I open the page in the webview of my client's android app, it always take more than 5000ms between first render call and the useEffect call.

here is my code:

import React, { useEffect, useState, useRef } from 'react';
import axios from 'axios';

const api = {
  ins: axios.create({
    baseURL: 'https://new.h5no1.com/apg-great-china-3/api'
  })
};

function App() {
  const [data, setData] = useState();
  const t = useRef(Date.now());
  useEffect(() => {
    console.log(Date.now() - t.current); // 5000+, useLayoutEffect log 30~50 only
    api.ins
      .post('/user/is_on_list', {
        openid: 'xxx',
        openToken: 'xxx'
      })
      .then(res => {
        setData(JSON.stringify(res.data))
      });
  }, []);

  return
{data ? data : 'loading'}
;
}

export default App;

and when I change to use the useLayoutEffect, it works fine, the problem is, I don't why using useEffect can cause an issue here while just using it to fetch data from web api ?

the UA string I get from the webview of the app

Mozilla/5.0 (Linux; Android 9; MI 8 Lite Build/PKQ1.181007.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/72.0.3626.121 Mobile Safari/537.36 PARS/50601

I have tested on other android devices with the app, they all behaved the same.

and using componentDidMount works fine, too.


问:
Firestore Rule allowing overwrite
I have a users collection where each document contains a name field and and an access map.

```<code>"users" :[
   {
     "mHbVq5TUY7brlleejClKm71NBGI2": {
         "name": "Bob Johnson",
         "access": {
             "X0w1VaVIljR1Nc5u3Sbo" : true
         }
   }
]
</code>```

I would like the Firestore rules to allow creation of a new document only if it doesn't already exist and only if the person performing the action has had their email verified. For the update, only the user owning that node can perform the update, the name must be a string, and the access map should not be able to be changed. I tested my update and create rules in the simulator and they worked as expected. However, when I run a .set() it completely overwrites my entire node and removes the access map which I cannot have happen. I assume that a .set() is actually performing an update and thus meeting my update criteria. So, how do I prevent someone from completely overwriting my node. Thanks in advance...code below.

---CODE PERFORMING OVERWRITE

```<code>db.collection("users").doc("mHbVq5TUY7brlleejClKm71NBGI2").set(
  {
    name: "Bill Swanson",
  }
).catch(err => {
  console.log(err.message)
})
</code>```

---RULES

```<code>function incomingData() {
  return request.resource.data
}

function emailVerified() {
  return request.auth.token.email_verified;
}

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {

      function userExists(user_Id) {
        return exists(/databases/$(database)/documents/users/$(user_Id));
      }

        allow create: if !userExists(userId) && emailVerified();
        allow update: if request.auth.uid == userId
                      && !('access' in incomingData())
                      && request.resource.data.name is string;
         allow read: if request.auth.uid != null;
    }
  }
}
</code>```

答:
When using set(), If you're not sure whether the document exists, pass the option to merge the new data with any existing document to avoid overwriting entire documents.

Here's how to pass the option to merge the update with the existing document.

```<code>db.collection("users")
.doc("mHbVq5TUY7brlleejClKm71NBGI2")
.set(
   {
      name: "Bill Swanson"
   },
   {
      merge: true
   }
).catch(err => {
   console.log(err.message)
});
</code>```

Hope this helps.

Title: Firestore Rule allowing overwrite

Body:
I have a users collection where each document contains a name field and and an access map.

"users" :[
   {
     "mHbVq5TUY7brlleejClKm71NBGI2": {
         "name": "Bob Johnson",
         "access": {
             "X0w1VaVIljR1Nc5u3Sbo" : true
         }
   }
]

I would like the Firestore rules to allow creation of a new document only if it doesn't already exist and only if the person performing the action has had their email verified. For the update, only the user owning that node can perform the update, the name must be a string, and the access map should not be able to be changed. I tested my update and create rules in the simulator and they worked as expected. However, when I run a .set() it completely overwrites my entire node and removes the access map which I cannot have happen. I assume that a .set() is actually performing an update and thus meeting my update criteria. So, how do I prevent someone from completely overwriting my node. Thanks in advance...code below.

---CODE PERFORMING OVERWRITE

db.collection("users").doc("mHbVq5TUY7brlleejClKm71NBGI2").set(
  {
    name: "Bill Swanson",
  }
).catch(err => {
  console.log(err.message)
})

---RULES

function incomingData() {
  return request.resource.data
}

function emailVerified() {
  return request.auth.token.email_verified;
}

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {

      function userExists(user_Id) {
        return exists(/databases/$(database)/documents/users/$(user_Id));
      }

        allow create: if !userExists(userId) && emailVerified();
        allow update: if request.auth.uid == userId
                      && !('access' in incomingData())
                      && request.resource.data.name is string;
         allow read: if request.auth.uid != null;
    }
  }
}

Body:
When using set(), If you're not sure whether the document exists, pass the option to merge the new data with any existing document to avoid overwriting entire documents.

Here's how to pass the option to merge the update with the existing document.

db.collection("users")
.doc("mHbVq5TUY7brlleejClKm71NBGI2")
.set(
   {
      name: "Bill Swanson"
   },
   {
      merge: true
   }
).catch(err => {
   console.log(err.message)
});

Hope this helps.


问:
SOLR query with raw data and union multiple facet values
I am writing a SOLR query for faceted searching, and my fields can possibly have quotes or other bad characters in them, so I am using the raw operator to construct the query. However, if the user selects multiple facet values, I can't see how to use an OR in the query.

For example, the following returns results for a Manufacturer of Nike:

```<code>{!raw f=Manufacturer}Nike
</code>```

The following returns results only for a Manufacturer of Adidas:

```<code>{!raw f=Manufacturer}Nike OR {!raw f=Manufacturer}Adidas
</code>```

And the following returns no results:

```<code>{!raw f=Manufacturer}Nike OR Adidas
</code>```

Is there a way to do this?

答:
Have you considered escaping the special characters, instead of using the raw operator?
http://lucene.apache.org/java/2_4_0/queryparsersyntax.html#Escaping%20Special%20Characters

Escaping is pretty trivial to implement and the OR operator should work as expected.
Here's an example of how to escape the special characters in PHP:

```<code>static public function escapeSolrValue($string)
{
    $match = array('\\', '+', '-', '&', '|', '!', '(', ')', '{', '}', '[', ']', '^', '~', '*', '?', ':', '"', ';', ' ');
    $replace = array('\\\\', '\\+', '\\-', '\\&', '\\|', '\\!', '\\(', '\\)', '\\{', '\\}', '\\[', '\\]', '\\^', '\\~', '\\*', '\\?', '\\:', '\\"', '\\;', '\\ ');
    $string = str_replace($match, $replace, $string);

    return $string;
}
</code>```

Source: http://e-mats.org/2010/01/escaping-characters-in-a-solr-query-solr-url/

Body:
I am writing a SOLR query for faceted searching, and my fields can possibly have quotes or other bad characters in them, so I am using the raw operator to construct the query. However, if the user selects multiple facet values, I can't see how to use an OR in the query.

For example, the following returns results for a Manufacturer of Nike:

{!raw f=Manufacturer}Nike

The following returns results only for a Manufacturer of Adidas:

{!raw f=Manufacturer}Nike OR {!raw f=Manufacturer}Adidas

And the following returns no results:

{!raw f=Manufacturer}Nike OR Adidas

Is there a way to do this?

Body:
Have you considered escaping the special characters, instead of using the raw operator?
http://lucene.apache.org/java/2_4_0/queryparsersyntax.html#Escaping%20Special%20Characters

Escaping is pretty trivial to implement and the OR operator should work as expected.
Here's an example of how to escape the special characters in PHP:

static public function escapeSolrValue($string)
{
    $match = array('\\', '+', '-', '&', '|', '!', '(', ')', '{', '}', '[', ']', '^', '~', '*', '?', ':', '"', ';', ' ');
    $replace = array('\\\\', '\\+', '\\-', '\\&', '\\|', '\\!', '\\(', '\\)', '\\{', '\\}', '\\[', '\\]', '\\^', '\\~', '\\*', '\\?', '\\:', '\\"', '\\;', '\\ ');
    $string = str_replace($match, $replace, $string);

    return $string;
}

Source: http://e-mats.org/2010/01/escaping-characters-in-a-solr-query-solr-url/