问:
Elegant way to get ExternalInterface working with all browsers
I want to call a function inside a Flash movie from javascript, using the ExternalInterface class. The problem is that to get it to work with Firefox I need to use the embed element and with the rest I have to get the object element. To solve it, I gave different ids to that two elements and depending on the user agent I select one or the other:

```<code> function getMovie(movieName) {

    alert(navigator.userAgent);
     if (navigator.userAgent.indexOf("Firefox") != -1) {
         return document["flash_embed"];
     } else {
         return document["flash_object"];
     }
 }
</code>```

This works, but it is not very elegant and it may not work with other browsers... Do you know a better way to do this?

答: Use swfobject to embed your flash movie, and then use it to retrieve the correct id.</p>

Body:
I want to call a function inside a Flash movie from javascript, using the ExternalInterface class. The problem is that to get it to work with Firefox I need to use the embed element and with the rest I have to get the object element. To solve it, I gave different ids to that two elements and depending on the user agent I select one or the other:

 function getMovie(movieName) {

    alert(navigator.userAgent);
     if (navigator.userAgent.indexOf("Firefox") != -1) {
         return document["flash_embed"];
     } else {
         return document["flash_object"];
     }
 }

This works, but it is not very elegant and it may not work with other browsers... Do you know a better way to do this?


来源: stackexchange

问:
Ive got a problem with updating my ComboBox, as soon as I recall the fill ComboBox I get all duplicates
Im trying to update my ComboBox as soon as ive made a new Capture file with data in it. If I close the form and reopen it, its obviously updated but that seems like a cheap way to program it. (To quickly close the form and open a new one) So far when i recall the method to refill the ComboBox it seems to include existing data and hardcopies everything.

My code as for now:

As soon as the form load this is executed:

```<code>    private void FormCapSave_Load(object sender, EventArgs e)
    {
        DirectoryInfo(@"C:\Users\pc\Documents\textfolder");
        FileInfo[] Files = d.GetFiles("*.cap");
        foreach (FileInfo file in Files)
        {
            if (!comboBoxSaveCap.Items.Contains(file))
            {
                comboBoxSaveCap.Items.Add(file.ToString());
            }
        }
</code>```

Followed by the button to add a new Cap file:

```<code>    private void buttonFormSaveAdd_Click(object sender, EventArgs e)
    {
        Form1.AfterNamingCapFile();
        if (Program.MainForm.boolSave == false)
        {
            labelFormSaveException.ForeColor = Color.Tomato;
            labelFormSaveException.Text = "Cap exists";
        }
        else
        {
            labelFormSaveException.ForeColor = Color.Green;
            labelFormSaveException.Text = "Cap file added";
            ResetForm();
        }
    }
</code>```

My ResetForm(); is basically a copy from the first on load method:

```<code>    private void ResetForm()
    {
        DirectoryInfo(@"C:\Users\pc\Documents\textfolder");
        FileInfo[] Files = d.GetFiles("*.cap");
        foreach (FileInfo file in Files)
        {
            if (!comboBoxSaveCap.Items.Contains(file))
            {
                comboBoxSaveCap.Items.Add(file.ToString());
            }
        }
    }
</code>```

答:
You need to clear the contents of your combobox before re-populating it.</p>

```<code>    private void ResetForm()
    {
        DirectoryInfo d = new
        DirectoryInfo(@"C:\Users\pc\Documents\textfolder");
        FileInfo[] Files = d.GetFiles("*.cap");
        comboBoxSaveCap.Items.Clear(); // Missing this bit
        foreach (FileInfo file in Files)
        {
            if (!comboBoxSaveCap.Items.Contains(file))
            {
                comboBoxSaveCap.Items.Add(file.ToString());
            }
        }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Im trying to update my ComboBox as soon as ive made a new Capture file with data in it. If I close the form and reopen it, its obviously updated but that seems like a cheap way to program it. (To quickly close the form and open a new one) So far when i recall the method to refill the ComboBox it seems to include existing data and hardcopies everything.

My code as for now:

As soon as the form load this is executed:

    private void FormCapSave_Load(object sender, EventArgs e)
    {
        DirectoryInfo(@"C:\Users\pc\Documents\textfolder");
        FileInfo[] Files = d.GetFiles("*.cap");
        foreach (FileInfo file in Files)
        {
            if (!comboBoxSaveCap.Items.Contains(file))
            {
                comboBoxSaveCap.Items.Add(file.ToString());
            }
        }

Followed by the button to add a new Cap file:

    private void buttonFormSaveAdd_Click(object sender, EventArgs e)
    {
        Form1.AfterNamingCapFile();
        if (Program.MainForm.boolSave == false)
        {
            labelFormSaveException.ForeColor = Color.Tomato;
            labelFormSaveException.Text = "Cap exists";
        }
        else
        {
            labelFormSaveException.ForeColor = Color.Green;
            labelFormSaveException.Text = "Cap file added";
            ResetForm();
        }
    }

My ResetForm(); is basically a copy from the first on load method:

    private void ResetForm()
    {
        DirectoryInfo(@"C:\Users\pc\Documents\textfolder");
        FileInfo[] Files = d.GetFiles("*.cap");
        foreach (FileInfo file in Files)
        {
            if (!comboBoxSaveCap.Items.Contains(file))
            {
                comboBoxSaveCap.Items.Add(file.ToString());
            }
        }
    }

Body:
You need to clear the contents of your combobox before re-populating it.

    private void ResetForm()
    {
        DirectoryInfo d = new
        DirectoryInfo(@"C:\Users\pc\Documents\textfolder");
        FileInfo[] Files = d.GetFiles("*.cap");
        comboBoxSaveCap.Items.Clear(); // Missing this bit
        foreach (FileInfo file in Files)
        {
            if (!comboBoxSaveCap.Items.Contains(file))
            {
                comboBoxSaveCap.Items.Add(file.ToString());
            }
        }
    }


问:
Uncaught ReferenceError: False is not defined in python django template
I am getting an Uncaught ReferenceError: False is not defined error while trying to access a Python dictionary variable in a Django template.

I have tried escaping with safe, but it does not work:

result = {'test1' : [{'var1': 'PLANNED', 'var2': 'description', 'var3': False},{'var1':'PLANNED', 'var2':'description', 'var3': True}], 'test2' : [{'var1': 'PLANNED', 'var2': 'description', 'var3': False},{'var1':'PLANNED', 'var2':'description', 'var3': True}]}
return render(request, 'users/team.html', {'team' : team, 'result ' : result })
```

<p>I am accessing this in my HTML as below:</p>

```var params= {{result |safe}};
```

How can I assign this result to a variable in a Django template?

答:
The issue is that you're effectively writing var params = ... False ...; in JavaScript. However, false in JS is written as false, not False! Note the capitalization difference. This results in the JS VM trying to in part assign the value of the variable False to the variable params. Unfortunately, you haven't defined a variable called False! Hence, a ReferenceError.

One approach to fix this issue is chaining with the json_script filter:

```<code>{{ result|json_script:"params-data" }}
<script>
    var value = JSON.parse(document.getElementById('params-data').textContent);
</script>
</code>```

Another approach is to manually encode/decode the result as JSON. e.g.

```<code>import json
return render(request, 'users/team.html', {'team' : team, 'result ' : json.dumps(result) })
</code>```

and the

```<code>var params = JSON.parse('{{result|safe}}');
</code>```

The first option is clearly preferable for its brevity and more straightforward nature.

Body:
I am getting an Uncaught ReferenceError: False is not defined error while trying to access a Python dictionary variable in a Django template.

I have tried escaping with safe, but it does not work:

result = {'test1' : [{'var1': 'PLANNED', 'var2': 'description', 'var3': False},{'var1':'PLANNED', 'var2':'description', 'var3': True}], 'test2' : [{'var1': 'PLANNED', 'var2': 'description', 'var3': False},{'var1':'PLANNED', 'var2':'description', 'var3': True}]}
return render(request, 'users/team.html', {'team' : team, 'result ' : result })

I am accessing this in my HTML as below:

var params= {{result |safe}};

How can I assign this result to a variable in a Django template?

Body:
The issue is that you're effectively writing var params = ... False ...; in JavaScript. However, false in JS is written as false, not False! Note the capitalization difference. This results in the JS VM trying to in part assign the value of the variable False to the variable params. Unfortunately, you haven't defined a variable called False! Hence, a ReferenceError.

One approach to fix this issue is chaining with the json_script filter:

{{ result|json_script:"params-data" }}
<script>
    var value = JSON.parse(document.getElementById('params-data').textContent);
</script>

Another approach is to manually encode/decode the result as JSON. e.g.

import json
return render(request, 'users/team.html', {'team' : team, 'result ' : json.dumps(result) })

and the

var params = JSON.parse('{{result|safe}}');

The first option is clearly preferable for its brevity and more straightforward nature.


问:
Logout logic is not working with basic authentication
This is my logout code. It is getting redirected to logout.done but, if I again go to hello I'm still able to access it.

```<code>public void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().authorizeRequests().anyRequest().authenticated().antMatchers(HttpMethod.GET, "/hello/**").hasRole("user")
    .and()
    .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
    .logoutSuccessUrl("/logout.done").deleteCookies("JSESSIONID")
    .invalidateHttpSession(true);
}
</code>```

What is wrong here?

答:
This code worked for me:</p>

```<code>public void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().authorizeRequests().anyRequest().authenticated().antMatchers(HttpMethod.GET, "/hello/**").hasRole("user").and().formLogin().and()
    .httpBasic()
    .and()
    .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
    .logoutSuccessUrl("/logout.done").deleteCookies("JSESSIONID")
    .invalidateHttpSession(true).clearAuthentication(true);
}
</code>```

Body:
This is my logout code. It is getting redirected to logout.done but, if I again go to hello I'm still able to access it.

public void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().authorizeRequests().anyRequest().authenticated().antMatchers(HttpMethod.GET, "/hello/**").hasRole("user")
    .and()
    .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
    .logoutSuccessUrl("/logout.done").deleteCookies("JSESSIONID")
    .invalidateHttpSession(true);
}

What is wrong here?

Body:
This code worked for me:

public void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().authorizeRequests().anyRequest().authenticated().antMatchers(HttpMethod.GET, "/hello/**").hasRole("user").and().formLogin().and()
    .httpBasic()
    .and()
    .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
    .logoutSuccessUrl("/logout.done").deleteCookies("JSESSIONID")
    .invalidateHttpSession(true).clearAuthentication(true);
}


问:
split by \r in a file instead of \n in python
I have a log file with contain both "\n" and "\r\n".

I tried spliting by "\r" and it returns only 1 element. I suspect python might have remove them when reading the file.

Is there a way to only split by "\r\n" as I don't want to split the stacktraces.

答:
If you are using Python 3 and open text file you need to inform Python, that you wants keep your newlines untouched following way:

```<code>open('filename.txt','r',newline='')
</code>```

Otherwise \r\n and \r and \n will be replaced with \n

(relevant documentation)

Body:
If you are using Python 3 and open text file you need to inform Python, that you wants keep your newlines untouched following way:

open('filename.txt','r',newline='')

Otherwise \r\n and \r and \n will be replaced with \n

(relevant documentation)


问:
How to insert into a table variable with a dynamic query?
I tried to develop this stored procedure using a temp table but that wouldn't work so I switched to using a table variable.  I need to execute an interim dynamic query into the table variable and then I use that table variable to execute the final query.  The problem is that I receive an error "must declare scalar variable @clms".  I assume that Exec doesn't have scope for the table variable?</p>

```<code>DECLARE @qry nvarchar(4000)
DECLARE @clms TABLE (mastcatname nvarchar(50),engdtlbeta decimal (18,4))
SET @qry='INSERT INTO @clms
          SELECT distinct replace(mastcatname, '' '', '''') as mastcatname,
                 engdtlbeta
          FROM vw_Scorecard
          WHERE empsurveyid=' + cAST(@EmpSurveyID AS nvarchar(10)) + '
               AND UnitID IN (' + @UnitIDs + ')
          ORDER BY engdtlbeta desc, MastCatName'

EXEC(@qry)

DECLARE @cols nvarchar(1000)
SELECT @cols=COALESCE (@cols + ',[' + mastcatname + ']', '[' + mastcatname + ']')
FROM @clms

SET @qry='SELECT UnitName ,
                 ParentName, ' + @cols + '
          FROM (
                SELECT UnitName,
                    ParentName,
                    ScoreAvg,
                    replace(mastcatname, '' '','''') as mastcatname
                FROM vw_Scorecard
                WHERE UnitID IN (' + @UnitIDs + ')
                    AND EmpSurveyID=' + cast(@EmpSurveyID as nvarchar(5)) + ' ) p
          PIVOT
            (SUM(ScoreAvg) FOR mastcatname in (' + @cols + ')) as pvt'

EXEC (@qry)
</code>```

答:
I found this attempting to do basically the same thing. I altered my SQL, and yes, it works! But then I thought, this is overcomplicating things. Why declare the table variable, insert, then select all in the dynamic SQL? Why not just select...</p>

```<code>DECLARE @t TABLE ( id INT )

DECLARE @q NVARCHAR(MAX) = 'select 1 union select 2'

INSERT INTO @t
EXEC(@q)

SELECT * FROM @t
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I tried to develop this stored procedure using a temp table but that wouldn't work so I switched to using a table variable.  I need to execute an interim dynamic query into the table variable and then I use that table variable to execute the final query.  The problem is that I receive an error "must declare scalar variable @clms".  I assume that Exec doesn't have scope for the table variable?

DECLARE @qry nvarchar(4000)
DECLARE @clms TABLE (mastcatname nvarchar(50),engdtlbeta decimal (18,4))
SET @qry='INSERT INTO @clms
          SELECT distinct replace(mastcatname, '' '', '''') as mastcatname,
                 engdtlbeta
          FROM vw_Scorecard
          WHERE empsurveyid=' + cAST(@EmpSurveyID AS nvarchar(10)) + '
               AND UnitID IN (' + @UnitIDs + ')
          ORDER BY engdtlbeta desc, MastCatName'

EXEC(@qry)

DECLARE @cols nvarchar(1000)
SELECT @cols=COALESCE (@cols + ',[' + mastcatname + ']', '[' + mastcatname + ']')
FROM @clms

SET @qry='SELECT UnitName ,
                 ParentName, ' + @cols + '
          FROM (
                SELECT UnitName,
                    ParentName,
                    ScoreAvg,
                    replace(mastcatname, '' '','''') as mastcatname
                FROM vw_Scorecard
                WHERE UnitID IN (' + @UnitIDs + ')
                    AND EmpSurveyID=' + cast(@EmpSurveyID as nvarchar(5)) + ' ) p
          PIVOT
            (SUM(ScoreAvg) FOR mastcatname in (' + @cols + ')) as pvt'

EXEC (@qry)

Body:
I found this attempting to do basically the same thing. I altered my SQL, and yes, it works! But then I thought, this is overcomplicating things. Why declare the table variable, insert, then select all in the dynamic SQL? Why not just select...

DECLARE @t TABLE ( id INT )

DECLARE @q NVARCHAR(MAX) = 'select 1 union select 2'

INSERT INTO @t
EXEC(@q)

SELECT * FROM @t


问:
How to create a txt file with a String content and download that txt file
I am using java and struts. I have a scenario where there is 'Download' link in the page. After clicking on this link the control goes to the Action class, where I have String content which I need to write to a .txt file and then download that txt file.

Eventually whenever we click on the download link, we should be able to download a txt file having content a particular string.

I used below piece of code,

```<code>FileOutputStream outputStream = new FileOutputStream(fileNameWithDirectory);
outputStream.write(fileContentString.getBytes());
outputStream.close();
ActionForward forward = new ActionForward("doc/" + filename);
forward.setName(filename);
forward.setRedirect(true);
return forward;
</code>```

Also I tried with FileWriter in place of FileOutputStream like,

```<code>FileWriter fileWriter = new FileWriter(fileNameWithDirectory);
fileWriter.write(fileContentString);
fileWriter.flush();
fileWriter.close();
</code>```

But always instead of downloading the txt file, the control opens a new window where the String content is written.
Please suggest me, how would I able to download that .txt file.

答:
Convert your text file to stream. and set content type as you wanted to download.
response.setContentType("application/pdf");

```<code>try {
      // get your file as InputStream
      InputStream is = ...;

      // copy it to response's OutputStream
      org.apache.commons.io.IOUtils.copy(is, convertedTextFiletoStream);

    } catch (IOException ex) {
      log.info("Error writing file to output stream. Filename was '{}'", fileName, ex);
      throw new RuntimeException("IOError writing file to output stream");
    }
</code>```

Body:
I am using java and struts. I have a scenario where there is 'Download' link in the page. After clicking on this link the control goes to the Action class, where I have String content which I need to write to a .txt file and then download that txt file.

Eventually whenever we click on the download link, we should be able to download a txt file having content a particular string.

I used below piece of code,

FileOutputStream outputStream = new FileOutputStream(fileNameWithDirectory);
outputStream.write(fileContentString.getBytes());
outputStream.close();
ActionForward forward = new ActionForward("doc/" + filename);
forward.setName(filename);
forward.setRedirect(true);
return forward;

Also I tried with FileWriter in place of FileOutputStream like,

FileWriter fileWriter = new FileWriter(fileNameWithDirectory);
fileWriter.write(fileContentString);
fileWriter.flush();
fileWriter.close();

But always instead of downloading the txt file, the control opens a new window where the String content is written.
Please suggest me, how would I able to download that .txt file.

Body:
Convert your text file to stream. and set content type as you wanted to download.
response.setContentType("application/pdf");

try {
      // get your file as InputStream
      InputStream is = ...;

      // copy it to response's OutputStream
      org.apache.commons.io.IOUtils.copy(is, convertedTextFiletoStream);

    } catch (IOException ex) {
      log.info("Error writing file to output stream. Filename was '{}'", fileName, ex);
      throw new RuntimeException("IOError writing file to output stream");
    }


问:
Unknown Property – yii\base\UnknownPropertyException for behavior method
I have set some properties in behavior() method and I'm getting this error

```<code>public function behaviors()
{
    return [
        'access'=>[
            'class'=> AccessControl::className(),
            'only'=>['create','update'],
            'rules'=>[
                'allow'=>true,
                'roles'=>['@'],
            ],

        ],
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'delete' => ['POST'],
            ],
        ],
    ];
}
</code>```

please someone see it to solve

答:
AccessControl::$rules should be array of rules, so you need something like this:

```<code>'access' => [
    'class' => AccessControl::className(),
    'only' => ['create','update'],
    'rules' => [
        [
            'allow' => true,
            'roles' => ['@'],
        ],
    ],
],
</code>```

Body:
I have set some properties in behavior() method and I'm getting this error

public function behaviors()
{
    return [
        'access'=>[
            'class'=> AccessControl::className(),
            'only'=>['create','update'],
            'rules'=>[
                'allow'=>true,
                'roles'=>['@'],
            ],

        ],
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'delete' => ['POST'],
            ],
        ],
    ];
}

please someone see it to solve

Body:
AccessControl::$rules should be array of rules, so you need something like this:

'access' => [
    'class' => AccessControl::className(),
    'only' => ['create','update'],
    'rules' => [
        [
            'allow' => true,
            'roles' => ['@'],
        ],
    ],
],


问:
autoptimize + cache enabler: randomly single pages don't load stylesheet
To improve page speed and user experience, I've tested many plugins dedicated for this.
So based on real results and many online testing (gtmetrix, google pagespeed, webpagetest) I moved to Autoptimize + Cache Enabler plugin solution.

1) What happens

I don't know why but randomly, only on some pages or only one, the content is loaded but completely without any css stylesheet, so the page comes out quite empty and all is messed up.
Last time it happened, I've examined the page with chrome dev tools and I've noticed which the all autoptimize's stylesheets weren't there: like the site doesn't have any of my css.

Clearing first the cache of "Cache enabler" then the cache of "Autoptimize" everything turned nice again.

2) The problem

I think this happened after wordpress auto-uptades, but I'm not sure.
Anyway, the real problem is that if it happens randomly and not only with WP updates, I can't control the situation and know when purge the cache and when not.
So I could have "blank" pages for weeks and don't know anything about it: bounce +1000% :)

I've already set time duration of cache from  "Cache Enabler" setting on 48h, so it should refresh automatically. Is it the right time to set?
I cannot make the same for "Autoptimize" plugin because it does not provide this option of auto-purge.

Before I change everything and move to other plugins and many other tests, does anybody know why this is happening and how I can fix it? Maybe disabling some optimizing setting on both plugins?

P.S.
Unfortunately I can't provide you with the error page because it happens randomly and I can't generate the error by myself.

Autoptimize + cache enabler problems (maybe plugin configuration settings?)

答:
Please Use W3 total cache plugin instead of Cache Enabler plugin. It is working fine for me. I have use Autoptimize with w3 total cache plugin on multiple sites. No CSS and JQuery conflict by using this.

```<code>https://wordpress.org/plugins/w3-total-cache/
</code>```

Body:
Please Use W3 total cache plugin instead of Cache Enabler plugin. It is working fine for me. I have use Autoptimize with w3 total cache plugin on multiple sites. No CSS and JQuery conflict by using this.

https://wordpress.org/plugins/w3-total-cache/


问:
Backup and restore some records of an elasticsearch index
I wish to take a backup of some records(eg latest 1 million records only) of an Elasticsearch index and restore this backup on a different machine. It would be better if this could be done using available/built-in Elasticsearch features.

I've tried Elasticsearch snapshot and restore (following code), but looks like it takes a backup of the whole index, and not selective records.

```<code>    curl -H 'Content-Type: application/json'  -X PUT "localhost:9200/_snapshot/es_data_dump?pretty=true" -d '
    {
      "type": "fs",
      "settings": {
        "compress" : true,
        "location": "es_data_dump"
      }
    }'

    curl -H 'Content-Type: application/json'  -X PUT "localhost:9200/_snapshot/es_data_dump/snapshot1?wait_for_completion=true&pretty=true" -d '
    {
      "indices" : "index_name",
      "type": "fs",
      "settings": {
        "compress" : true,
        "location": "es_data_dump"
      }
    }'
</code>```

The format of backup could be anything, as long as it can be successfully restored on a different machine.

答:
you can use _reinex API. it can take any query. after reindex, you have a new index as backup, which contains requested records. easily copy it where ever you want.

complete information is here: https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html

Body:
I wish to take a backup of some records(eg latest 1 million records only) of an Elasticsearch index and restore this backup on a different machine. It would be better if this could be done using available/built-in Elasticsearch features.

I've tried Elasticsearch snapshot and restore (following code), but looks like it takes a backup of the whole index, and not selective records.

    curl -H 'Content-Type: application/json'  -X PUT "localhost:9200/_snapshot/es_data_dump?pretty=true" -d '
    {
      "type": "fs",
      "settings": {
        "compress" : true,
        "location": "es_data_dump"
      }
    }'

    curl -H 'Content-Type: application/json'  -X PUT "localhost:9200/_snapshot/es_data_dump/snapshot1?wait_for_completion=true&pretty=true" -d '
    {
      "indices" : "index_name",
      "type": "fs",
      "settings": {
        "compress" : true,
        "location": "es_data_dump"
      }
    }'

The format of backup could be anything, as long as it can be successfully restored on a different machine.


问:
How to stop Highmaps on mouse hover to change SVG path orders
In all Highmaps when we hover on any particular country, the hoverd country SVG path put at the bottom in order to show hovered country on the top of others (the way we achieve z-index in svg).
I don't want Highmaps on mouse hover to change SVG path orders.</p>

答:
You can wrap zIndexSetter method to call it only if the element is not a path:

```<code>(function(H) {
    H.wrap(H.SVGElement.prototype, 'zIndexSetter', function(proceed, value, key, el) {
        if (!el || (el && el.tagName !== 'path')) {
            return proceed.apply(this, Array.prototype.slice.call(arguments, 1));
        }
    });
}(Highcharts));
</code>```

Live demo: https://jsfiddle.net/BlackLabel/31a0x4sL/

Docs: https://www.highcharts.com/docs/extending-highcharts

Body:
You can wrap zIndexSetter method to call it only if the element is not a path:

(function(H) {
    H.wrap(H.SVGElement.prototype, 'zIndexSetter', function(proceed, value, key, el) {
        if (!el || (el && el.tagName !== 'path')) {
            return proceed.apply(this, Array.prototype.slice.call(arguments, 1));
        }
    });
}(Highcharts));

Live demo: https://jsfiddle.net/BlackLabel/31a0x4sL/

Docs: https://www.highcharts.com/docs/extending-highcharts


问:
Why "Get Suites By Test Case Id" REST call returns "The request is invalid"?
I am trying to retrieve all test suits which contain a specific test case by test case ID.

I'm sending the following GET call:

```<code>GET https://dev.azure.com/{organization}/{DefaultCollection/}_apis/test/suites?testCaseId={testCaseId}&api-version=5.0
</code>```

Instead of receiving the list of test suits I get the following response:

```<code>{"count":1,"value":{"Message":"The request is invalid."}}
</code>```

If I add project to the request url, I get Page not found 404 error, so I assume, project name should not be there. But even without it I get request is invalid message.

Test Case ID is correct, I've tried several, and the response was the same.

What am I missing with this REST call? I didn't have similar issues with other calls.

I used the following Microsoft resource for reference:

https://learn.microsoft.com/en-us/rest/api/azure/devops/test/test%20%20suites/get%20suites%20by%20test%20case%20id?view=azure-devops-rest-5.0

答:
Probably Azure DevOps Server 2019 not support in api-version-5.0 in this API call, so just need to remove it (then the call did with the default correct version):

```<code>http://azure-devops-server:8080/tfs/collection/_apis/test/suites?testCaseId=1
</code>```

Body:
I am trying to retrieve all test suits which contain a specific test case by test case ID.

I'm sending the following GET call:

GET https://dev.azure.com/{organization}/{DefaultCollection/}_apis/test/suites?testCaseId={testCaseId}&api-version=5.0

Instead of receiving the list of test suits I get the following response:

{"count":1,"value":{"Message":"The request is invalid."}}

If I add project to the request url, I get Page not found 404 error, so I assume, project name should not be there. But even without it I get request is invalid message.

Test Case ID is correct, I've tried several, and the response was the same.

What am I missing with this REST call? I didn't have similar issues with other calls.

I used the following Microsoft resource for reference:

https://learn.microsoft.com/en-us/rest/api/azure/devops/test/test%20%20suites/get%20suites%20by%20test%20case%20id?view=azure-devops-rest-5.0

Body:
Probably Azure DevOps Server 2019 not support in api-version-5.0 in this API call, so just need to remove it (then the call did with the default correct version):

http://azure-devops-server:8080/tfs/collection/_apis/test/suites?testCaseId=1


问:
How to remove unwanted keys from rest-assured response object and assert remaining object data with constant variable having json string using java
In rest-assured test cases I am getting response as mentioned, where I want to remove keys such as "updated_at", "deleted_at", "created_at" and "notice" and then assert this response object with expected json string constant which contains 'settings'

```<code>{
    "notice": "The Settings are updated successfully.",
    "settings": {
    "push_notification": {
        "enabled": true,
        "credentials": [{
            "key": "value"
        }],
        "service_name": "API Testing"
    },
    "created_at": "2019-05-04T14:52:32.773Z",
    "deleted_at": "false",
    "updated_at": "2019-05-07T11:23:22.781Z"
    }
}
</code>```

For given response the expected json string is...

```<code>public static String SETTING_EXPECTED = "{\"push_notification\": {\"enabled\": true, \"credentials\": [{\"key\": \"value\"}], \"service_name\": \"API Testing\"}}"
</code>```

Please help me with creating a common method using java which can be reuse for response assertions in all the test cases.

答:
To delete keys from response you can use below code I am using jayway jsonpath library, you need to pass Json Response and field name jsonPath, in case your it will be  "$.settings.created_at" :</p>

```<code>public String deleteFieldNameFromResponse(String jsonResponse, String fieldToDelete)
            throws ParseException, FileNotFoundException, IOException {
        Object obj = null;
        JSONParser parser = new JSONParser();
        JsonPath jsonPath = null;
        DocumentContext docCtx = null;

        obj = parser.parse(jsonResponse);

        docCtx = JsonPath.parse(obj);

        docCtx.delete(fieldToDelete);

        jsonPath = JsonPath.compile("$");

        return docCtx.read(jsonPath).toString();
    }
</code>```

Body:
In rest-assured test cases I am getting response as mentioned, where I want to remove keys such as "updated_at", "deleted_at", "created_at" and "notice" and then assert this response object with expected json string constant which contains 'settings'

{
    "notice": "The Settings are updated successfully.",
    "settings": {
    "push_notification": {
        "enabled": true,
        "credentials": [{
            "key": "value"
        }],
        "service_name": "API Testing"
    },
    "created_at": "2019-05-04T14:52:32.773Z",
    "deleted_at": "false",
    "updated_at": "2019-05-07T11:23:22.781Z"
    }
}

For given response the expected json string is...

public static String SETTING_EXPECTED = "{\"push_notification\": {\"enabled\": true, \"credentials\": [{\"key\": \"value\"}], \"service_name\": \"API Testing\"}}"

Please help me with creating a common method using java which can be reuse for response assertions in all the test cases.

Body:
To delete keys from response you can use below code I am using jayway jsonpath library, you need to pass Json Response and field name jsonPath, in case your it will be  "$.settings.created_at" :

public String deleteFieldNameFromResponse(String jsonResponse, String fieldToDelete)
            throws ParseException, FileNotFoundException, IOException {
        Object obj = null;
        JSONParser parser = new JSONParser();
        JsonPath jsonPath = null;
        DocumentContext docCtx = null;

        obj = parser.parse(jsonResponse);

        docCtx = JsonPath.parse(obj);

        docCtx.delete(fieldToDelete);

        jsonPath = JsonPath.compile("$");

        return docCtx.read(jsonPath).toString();
    }


问:
ReactJS: How to change Text value on button click
I am creating a form in my App and need to add a quantity field in it. I have added a <Text> component from informed to add quantity field and used buttons to add increment and decrement feature.

But I am not able to set Text component value on button click. It seems like  I can only set initialValue for <Text> component.

```<code>import React, { Component } from 'react';
import { arrayOf, number, shape, string } from 'prop-types';

import classify from 'src/classify';
import defaultClasses from './quantity.css';
import { Text } from 'informed';

class Quantity extends Component {
    static propTypes = {
        classes: shape({
            root: string,
            increment_button: string,
            decrement_button: string,
            quantity_input: string
        }),
        items: arrayOf(
            shape({
                value: number
            })
        )
    };

    state = {
        quantity: 1,
        show: true,
        max: 9999,
        min: 1
    };

    incrementQty = () => {
        this.setState(prevState => {
            if(prevState.quantity < this.state.max) {
                return {
                    quantity: parseInt(prevState.quantity) + 1
                }
            } else {
                return null;
            }
        });
        /*this.setState({ quantity: parseInt(this.state.quantity) + 1 });*/
    };
    decrementQty = () => {
        this.setState(prevState => {
            if(prevState.quantity > this.state.min) {
                return {
                    quantity: parseInt(prevState.quantity) - 1
                }
            } else {
                return null;
            }
        });
        /*this.setState({ quantity: parseInt(this.state.quantity) - 1 });*/
    };
    setQuantity = quantity => this.setState({ quantity });
    handleChange = (event) => {
        this.setState({quantity: event.target.value});
    };

    render() {
        const { classes, ...restProps } = this.props;
        console.log(this.state.quantity);
        return (
            <div className={classes.root}>
            <span onClick={this.decrementQty} className={classes.decrement_button}>-</span>
            <Text
                initialValue = {`${this.state.min}`}
                className={classes.quantity_input}
                field="quantity"
                onChange={this.handleChange}
                value={this.state.quantity}
                label=""
            />
            <span onClick={this.incrementQty} className={classes.increment_button}>+</span>
            </div>
    );
    }
}

export default classify(defaultClasses)(Quantity);
</code>```

I have tried using value prop but its not working. If I am using uncontrolled html <input> field, the buttons and quantity increment decrement works but I don't want to use <input> element with my form.

答:
Maybe your code should be

```<code> onChange={quantity => this.handleChange(quantity)}
</code>```

and your code to handle state update

```<code>onChange = (e) => {
  this.setState({
    [e.target.name]: e.target.value
  });
}
</code>```

Body:
I am creating a form in my App and need to add a quantity field in it. I have added a <Text> component from informed to add quantity field and used buttons to add increment and decrement feature.

But I am not able to set Text component value on button click. It seems like  I can only set initialValue for <Text> component.

import React, { Component } from 'react';
import { arrayOf, number, shape, string } from 'prop-types';

import classify from 'src/classify';
import defaultClasses from './quantity.css';
import { Text } from 'informed';

class Quantity extends Component {
    static propTypes = {
        classes: shape({
            root: string,
            increment_button: string,
            decrement_button: string,
            quantity_input: string
        }),
        items: arrayOf(
            shape({
                value: number
            })
        )
    };

    state = {
        quantity: 1,
        show: true,
        max: 9999,
        min: 1
    };

    incrementQty = () => {
        this.setState(prevState => {
            if(prevState.quantity < this.state.max) {
                return {
                    quantity: parseInt(prevState.quantity) + 1
                }
            } else {
                return null;
            }
        });
        /*this.setState({ quantity: parseInt(this.state.quantity) + 1 });*/
    };
    decrementQty = () => {
        this.setState(prevState => {
            if(prevState.quantity > this.state.min) {
                return {
                    quantity: parseInt(prevState.quantity) - 1
                }
            } else {
                return null;
            }
        });
        /*this.setState({ quantity: parseInt(this.state.quantity) - 1 });*/
    };
    setQuantity = quantity => this.setState({ quantity });
    handleChange = (event) => {
        this.setState({quantity: event.target.value});
    };

    render() {
        const { classes, ...restProps } = this.props;
        console.log(this.state.quantity);
        return (

            -
            <Text
                initialValue = {`${this.state.min}`}
                className={classes.quantity_input}
                field="quantity"
                onChange={this.handleChange}
                value={this.state.quantity}
                label=""
            />
            +

    );
    }
}

export default classify(defaultClasses)(Quantity);

I have tried using value prop but its not working. If I am using uncontrolled html <input> field, the buttons and quantity increment decrement works but I don't want to use <input> element with my form.

Body:
Maybe your code should be

 onChange={quantity => this.handleChange(quantity)}

and your code to handle state update

onChange = (e) => {
  this.setState({
    [e.target.name]: e.target.value
  });
}


问:
Possible to remove included classes?
I am using a 3rd party file manager plugin on a CMS and I want to include an authentication check from a PHP framework I'm using. The authentication part works fine, just a simple include then the auth check, however there then seems to be some conflict between the included classes and those of the file manager. For example, I'm getting a "Class Kohana not found" error where a class belonging to the file manager is trying to instantiate a class belonging to the framework.

At the top of my file manager main entry file, I have the following:

```<code>//load Kohana framework for Authorisation
include('../../../../../admin/index.php');

// If not a valid authenticated user, kill page
if ( ! Auth::instance()->logged_in())
{
    die('Unauthorized');
}
</code>```

Having done the authentication, I no longer want the included files and classes, as these are seemingly conflicting with the file manager. Is there a way that I can do this, or am I misunderstanding what's going on here?

The error being thrown is in a file manager class - public_html/media/js/tiny_mce/plugins/ajaxfilemanager/inc/class.file.php [ 67 ]

```<code>function file($path=null)
{
    $this->__construct($path);
}
</code>```

答:
Class xyz not found is not a sign of a conflict - it the Kohana bootstrap that probably doesn't get loaded.

There's no way to "unload" classes within a PHP script. If two packages share a class name, you'll have to load them in separate scripts, or move one of them into a separate namespace (requires PHP 5.3+). But as said, in your case, you probably just need to load the correct bootstrap file to include the needed classes.

Title: Possible to remove included classes?

Body:
I am using a 3rd party file manager plugin on a CMS and I want to include an authentication check from a PHP framework I'm using. The authentication part works fine, just a simple include then the auth check, however there then seems to be some conflict between the included classes and those of the file manager. For example, I'm getting a "Class Kohana not found" error where a class belonging to the file manager is trying to instantiate a class belonging to the framework.

At the top of my file manager main entry file, I have the following:

//load Kohana framework for Authorisation
include('../../../../../admin/index.php');

// If not a valid authenticated user, kill page
if ( ! Auth::instance()->logged_in())
{
    die('Unauthorized');
}

Having done the authentication, I no longer want the included files and classes, as these are seemingly conflicting with the file manager. Is there a way that I can do this, or am I misunderstanding what's going on here?

The error being thrown is in a file manager class - public_html/media/js/tiny_mce/plugins/ajaxfilemanager/inc/class.file.php [ 67 ]

function file($path=null)
{
    $this->__construct($path);
}


问:
How to locate the code location that causes the application to receive SIGTTIN under linux?
One of my c++ applications will hang after running for an indeterminate length of time, because it is not terminated, so it cannot be restarted by the parent process.

It is known that SIGTTIN can prevent the program from being suspended by nohup or by using </dev/null to redirect standard input, but this does not solve the problem fundamentally.

So, does anyone know how to debug or locate the location of the code that produces the SIGTTIN signal?

// this is a example, exec command to get SIGTTIN: ./a.out &
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

int main(int argc, char* argv[]) {
        int len;
        char buf[64];

        while(1) {
                len = read(STDIN_FILENO, buf, 64);
                if (len > 0) {
                        write(STDOUT_FILENO, buf, len);
                }
                else {
                        perror("read");
                }
        }
        return 0;
}

```

答:
You launch your program in background doing ./a.out & but your program reads from stdin so you have that signal

From https://www.gnu.org/software/libc/manual/html_node/Job-Control-Signals.html :

Macro: int SIGTTIN

A process cannot read from the user’s terminal while it is running as a background job. When any process in a background job tries to read from the terminal, all of the processes in the job are sent a SIGTTIN signal. The default action for this signal is to stop the process. For more information about how this interacts with the terminal driver, see Access to the Terminal.

locate the location of the code that produces the SIGTTIN signal?

It is the read


答:
You're right, informed Text doesn't have a prop value, I found a trick on how to set the value of the Text on a click of a button.

You can create a ref using React.createRef to your Text then set the value via this ref.

```<code>class App extends React.Component {
  constructor(props) {
    super(props);
    this.ref = React.createRef();
  }
  state = {
    min: 10
  };
  changeQt = () => {
    this.ref.current.value = 20;
  };
  render() {
    return (
      <div className="App">
        <Text
          initialValue={`${this.state.min}`}
          field="quantity"
          onChange={this.handleChange}
          label=""
          ref={this.ref}
        />
        <button onClick={this.changeQt}>Click</button>
      </div>
    );
  }
}
</code>```

Demo here.

Title: ReactJS: How to change Text value on button click

Body:
You're right, informed Text doesn't have a prop value, I found a trick on how to set the value of the Text on a click of a button.

You can create a ref using React.createRef to your Text then set the value via this ref.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.ref = React.createRef();
  }
  state = {
    min: 10
  };
  changeQt = () => {
    this.ref.current.value = 20;
  };
  render() {
    return (
      <div className="App">
        <Text
          initialValue={`${this.state.min}`}
          field="quantity"
          onChange={this.handleChange}
          label=""
          ref={this.ref}
        />
        <button onClick={this.changeQt}>Click</button>
      </div>
    );
  }
}

Demo here.


问:
Is assigning two variables to items in the same list the best way to access and perform operations on those items?
Say I have a list

```<code>l = [1,2,3]
</code>```

and I want to sum each item in the list with every other item in the list. I could do this:

```<code>x = [(a, b) for a in l for b in l]
y = [(a + b) for a in l for b in l]

x = [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
y = [2, 3, 4, 3, 4, 5, 4, 5, 6]
</code>```

Is assigning two variables (a and b) to items in the same list (l) the best way to access and perform operations on those items? Is there a better way to do this?

I've looked at list methods and functions, and couldn't find any.

UPDATE

Many people recommended the itertools product function so I thought I'd include timings before I mark as answered:

```<code>mysetup = """
from itertools import product
l = [10, 15, 3, 7]
k = 17
"""
mycode = """
[i for i in product(l, repeat=2)]
"""

t = timeit.timeit(setup=mysetup, stmt=mycode, number=100000)
# 0.1505305

mysetup2 = """
l = [10, 15, 3, 7]
k = 17
"""
mycode2 = """
[(a, b) for a in l for b in l]
"""

t1 = timeit.timeit(setup=mysetup2, stmt=mycode2, number=100000)
# 0.1432976
</code>```

答:
Python provides built in method

```<code>from itertools import product
l = [1,2,3]
</code>```

Then generate the sum using list comprehension in a single step to be more efficent

```<code>result= [sum(i) for i in product(l, repeat= 2) ]

#result=[2, 3, 4, 3, 4, 5, 4, 5, 6]
</code>```

Body:
Say I have a list

l = [1,2,3]

and I want to sum each item in the list with every other item in the list. I could do this:

x = [(a, b) for a in l for b in l]
y = [(a + b) for a in l for b in l]

x = [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
y = [2, 3, 4, 3, 4, 5, 4, 5, 6]

Is assigning two variables (a and b) to items in the same list (l) the best way to access and perform operations on those items? Is there a better way to do this?

I've looked at list methods and functions, and couldn't find any.

UPDATE

Many people recommended the itertools product function so I thought I'd include timings before I mark as answered:

mysetup = """
from itertools import product
l = [10, 15, 3, 7]
k = 17
"""
mycode = """
[i for i in product(l, repeat=2)]
"""

t = timeit.timeit(setup=mysetup, stmt=mycode, number=100000)
# 0.1505305

mysetup2 = """
l = [10, 15, 3, 7]
k = 17
"""
mycode2 = """
[(a, b) for a in l for b in l]
"""

t1 = timeit.timeit(setup=mysetup2, stmt=mycode2, number=100000)
# 0.1432976

Body:
Python provides built in method

from itertools import product
l = [1,2,3]

Then generate the sum using list comprehension in a single step to be more efficent

result= [sum(i) for i in product(l, repeat= 2) ]

#result=[2, 3, 4, 3, 4, 5, 4, 5, 6]


问:
Linear regression using same variable twice
I'm trying to run a multivariate linear regression on a data set but the summary has one of my categorical variables appearing twice with different coefficient values.

Below is a snapshot of the dataset and the regression output.

''' data = read.csv("Data.csv")
data1 = select(data, Generosity, MALE, ECON, FIRST, FIELD, EXP, ECON300, ECON400, EMPLOY, STUDLOAN, DEBT)
head(data1)

reg1 = lm(Generosity~MALE + ECON + FIRST + FIELD + EXP + ECON300 + ECON400 + EMPLOY + STUDLOAN + DEBT, data = data1)
summary(reg1)'''

FIELDSOCSCI appears twice?

答:
Check in your dataframe if there is a second spelling of SOCSCI and if so, decide for one and change the other by replacing it in your code.
Acutally, lm(formula, data,...) should not result in two entries for the same variable.


问:
Why does instantiation of subclass work inside __init_subclass__, despite being an Abstract Base Class that is missing a method?
I'm trying to write a simple plugin system.

a) For this I found the following code using the 3.6 magic function __init_subclass__ https://stackoverflow.com/a/41924331/1506569 which is adapted from PEP 487, that registers every class on definition in the parent class in the plugins list.

b) I would now like to "force" the writer of the plugin to implement a specific method, that will be called by my program. Ideally, that would warn the user on import, that his plugin won't work but would not prevent the program from running. For this, I tried to add ABC as the parent class to the Plugin and adding an @abstractmethod.

My original attempt with ABC and __init_subclass__:

from abc import ABC, abstractmethod

class Plugin(ABC):
    plugins = []

    @classmethod
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        try:
            __class__.plugins.append(cls())  # Does not raise exception
        except Exception as e:
            print("Warning: Your plugin might not work, missing abstract method")

    @abstractmethod
    def do_something(self):
        ...

class Render(Plugin):
    def __init__(self):
        print("Render init")

    # does not implement 'do_something'

for plugin in Plugin.plugins:
    plugin.do_something()  # Calls 'do_something' on Render, without raising an exception
```

<p>The problem here is, that the instantiation <code>__class__.plugins.append(cls())</code> does not raise an exception, instead the instantiated <code>Render</code> object is added to the <code>plugins</code> list.
Calling the function <code>Render.do_something</code> (the loop at the bottom) does not raise an exception either. It does nothing.</p>

<p>A solution I found is described here: https://stackoverflow.com/a/54545842/1506569 which is simply comparing if the function objects on base class and child class are different (by using <strong>class</strong> and cls). This makes inheriting from ABC unnecessary though and seems more complicated than need be.</p>

<p>The second attempt, without ABC:</p>

<pre class="lang-py prettyprint-override"><code>class Plugin():
    plugins = []

    @classmethod
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        if getattr(cls, 'do_something') is getattr(__class__, 'do_something'):
            print("Warning: Your plugin might not work, missing 'do_something'")
        else:
            __class__.plugins.append(cls())

    def do_something(self):
        ...

class Render(Plugin):
    def __init__(self):
        print("Render init")

for plugin in Plugin.plugins:
    plugin.do_something()
</code>```

This version works, but seems convoluted to me and looks like it might break further down the line?

Is there an approach I missed? Why does the instantiation work?
Sorry if I missed a similar question, I tried searching for a long time.

答:
If you just want to force subclasses to implement a method, @abstractmethod is enough. You don't need init_subclass. Your code is correct, however, you have not instantiated Render anywhere. The abstract method will give you an error when creating objects, not classes. If you write Render(), you will actually get an error

Can't instantiate abstract class Render with abstract methods do_something

Body:
I'm trying to write a simple plugin system.

a) For this I found the following code using the 3.6 magic function __init_subclass__ https://stackoverflow.com/a/41924331/1506569 which is adapted from PEP 487, that registers every class on definition in the parent class in the plugins list.

b) I would now like to "force" the writer of the plugin to implement a specific method, that will be called by my program. Ideally, that would warn the user on import, that his plugin won't work but would not prevent the program from running. For this, I tried to add ABC as the parent class to the Plugin and adding an @abstractmethod.

My original attempt with ABC and __init_subclass__:

from abc import ABC, abstractmethod

class Plugin(ABC):
    plugins = []

    @classmethod
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        try:
            __class__.plugins.append(cls())  # Does not raise exception
        except Exception as e:
            print("Warning: Your plugin might not work, missing abstract method")

    @abstractmethod
    def do_something(self):
        ...

class Render(Plugin):
    def __init__(self):
        print("Render init")

    # does not implement 'do_something'

for plugin in Plugin.plugins:
    plugin.do_something()  # Calls 'do_something' on Render, without raising an exception

The problem here is, that the instantiation __class__.plugins.append(cls()) does not raise an exception, instead the instantiated Render object is added to the plugins list.
Calling the function Render.do_something (the loop at the bottom) does not raise an exception either. It does nothing.

A solution I found is described here: https://stackoverflow.com/a/54545842/1506569 which is simply comparing if the function objects on base class and child class are different (by using class and cls). This makes inheriting from ABC unnecessary though and seems more complicated than need be.

The second attempt, without ABC:

class Plugin():
    plugins = []

    @classmethod
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        if getattr(cls, 'do_something') is getattr(__class__, 'do_something'):
            print("Warning: Your plugin might not work, missing 'do_something'")
        else:
            __class__.plugins.append(cls())

    def do_something(self):
        ...

class Render(Plugin):
    def __init__(self):
        print("Render init")

for plugin in Plugin.plugins:
    plugin.do_something()

This version works, but seems convoluted to me and looks like it might break further down the line?

Is there an approach I missed? Why does the instantiation work?
Sorry if I missed a similar question, I tried searching for a long time.


问:
Is there a method for String conversion to Title Case?
Are there any built in methods available to convert a string into Title Case format?</p>

答:
This should work:</p>

```<code>String str="i like pancakes";
String arr[]=str.split(" ");
String strNew="";
for(String str1:arr)
{
    Character oldchar=str1.charAt(0);
    Character newchar=Character.toUpperCase(str1.charAt(0));
    strNew=strNew+str1.replace(oldchar,newchar)+" ";
}
System.out.println(strNew);
</code>```

OwnerDisplayName: Raji

Body:
This should work:

String str="i like pancakes";
String arr[]=str.split(" ");
String strNew="";
for(String str1:arr)
{
    Character oldchar=str1.charAt(0);
    Character newchar=Character.toUpperCase(str1.charAt(0));
    strNew=strNew+str1.replace(oldchar,newchar)+" ";
}
System.out.println(strNew);


问:
In Room drop an Entity and recreate with updated changes
I'm using Room database in my application. I've some changes in columns of the Entity , so in DB Migration I want to drop the old table and recreate it with the updated Entity. But after Drop Table query instead of writing a long query to create the table again, can we just pass the entity model somehow or tell the DB to recreate the entity? Because my Entity has a number of columns,relations and onDelete rule in it so query would be complex.

Following is the Entity:

```<code>@Entity(tableName = MediaTags.TABLE_NAME_UPLOAD_MEDIA,
        foreignKeys =
        @ForeignKey(
                entity = PostUpload.class,
                parentColumns = PostTags.COLUMN_UPLOAD_POST_LOCAL_ID,
                childColumns = MediaTags.COLUMN_UPLOAD_MEDIA_POST_ID,
                onDelete = CASCADE),
        indices = {@Index(MediaTags.COLUMN_UPLOAD_MEDIA_POST_ID)})
public class MediaUpload {
    @Ignore
    public final static int MEDIA_TYPE_IMAGE = 1;
    @Ignore
    public final static int MEDIA_TYPE_VIDEO = 2;

    @PrimaryKey
    @NonNull
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_KEY)
    public String mediaKey; // unique key
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_HASH_MD5)
    public String hashMd5;   // hashMd5 of file, for now we are sending it empty, in future will be used
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_TYPE)
    public int mediaType;  // picture or video
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_STATUS)
    public int status = UploadStatus.NOT_COMPRESSED; // upload and edit statues
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_FILE_PATH)
    public String filePath;
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_POST_ID)
    public String postId;
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_THUMBNAIL)
    public String thumbnail;  // thumbnail in case of videos
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_OVERLAY_PATH)
    public String overlayPath;  // overlay image containing all the editing

}
</code>```

答:
I believe that you could use the following :-

```<code>private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
    @Override

    public void migrate(SupportSQLiteDatabase database) {
            //Create the new table BUT with a different name
            database.execSQL("DROP TABLE IF EXISTS new_mediatags;"); -- just in case but not really required
            database.execSQL("CREATE TABLE new_mediatags (the_column_definitions_you_want)");
            //Copy existing data into the new table (if required)
            database.execSQL("INSERT INTO new_mediatags SELECT the_columns_you_are keeping,null;");
            //Rename the original table
            database.execSQL("ALTER TABLE mediatags RENAME TO old_mediatags;");
            //Rename the new table to the original name
            database.execSQL("ALTER TABLE new_mediatags RENAME TO mediatags;");
            //Drop the renamed original table
            database.execSQL("DROP TABLE IF EXISTS old_mediatags;");
    }
};
</code>```

This assumes that you want to keep the existing data, if not then simply don't copy the data.

As an example consider the following :-

```<code>-- Create the original and load with some data
DROP TABLE If EXISTS mediatags;
CREATE TABLE IF NOT EXISTS mediatags (col1, col2, col3);
INSERT INTO mediatags VALUES('A','B','C'),('D','E','F');
SELECT * FROM mediatags;

-- The code that would be used
DROP TABLE IF EXISTS new_mediatags;
CREATE TABLE IF NOT EXISTS new_mediatags (col1, col3, col4); -- note no col2 but new col added as col4
INSERT INTO new_mediatags SELECT col1,col3,null FROM mediatags; -- copy existing data
ALTER TABLE mediatags RENAME TO old_mediatags;
ALTER TABLE new_mediatags RENAME TO mediatags;
DROP TABLE old_mediatags;

SELECT * FROM mediatags; -- output the data for the demo
</code>```

The first 4 lines just create the original table, load it with some data and outpts the data as per :-

The other lines, swap the original table for the new table, removing col2 and adding col4, copying the existing data (the new column will be null although a value could be supplied) and finally for the demo outputs the data in the changed table as per :-

Body:
I'm using Room database in my application. I've some changes in columns of the Entity , so in DB Migration I want to drop the old table and recreate it with the updated Entity. But after Drop Table query instead of writing a long query to create the table again, can we just pass the entity model somehow or tell the DB to recreate the entity? Because my Entity has a number of columns,relations and onDelete rule in it so query would be complex.

Following is the Entity:

@Entity(tableName = MediaTags.TABLE_NAME_UPLOAD_MEDIA,
        foreignKeys =
        @ForeignKey(
                entity = PostUpload.class,
                parentColumns = PostTags.COLUMN_UPLOAD_POST_LOCAL_ID,
                childColumns = MediaTags.COLUMN_UPLOAD_MEDIA_POST_ID,
                onDelete = CASCADE),
        indices = {@Index(MediaTags.COLUMN_UPLOAD_MEDIA_POST_ID)})
public class MediaUpload {
    @Ignore
    public final static int MEDIA_TYPE_IMAGE = 1;
    @Ignore
    public final static int MEDIA_TYPE_VIDEO = 2;

    @PrimaryKey
    @NonNull
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_KEY)
    public String mediaKey; // unique key
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_HASH_MD5)
    public String hashMd5;   // hashMd5 of file, for now we are sending it empty, in future will be used
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_TYPE)
    public int mediaType;  // picture or video
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_STATUS)
    public int status = UploadStatus.NOT_COMPRESSED; // upload and edit statues
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_FILE_PATH)
    public String filePath;
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_POST_ID)
    public String postId;
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_THUMBNAIL)
    public String thumbnail;  // thumbnail in case of videos
    @ColumnInfo(name = MediaTags.COLUMN_UPLOAD_MEDIA_OVERLAY_PATH)
    public String overlayPath;  // overlay image containing all the editing

}

Body:
I believe that you could use the following :-

private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
    @Override

    public void migrate(SupportSQLiteDatabase database) {
            //Create the new table BUT with a different name
            database.execSQL("DROP TABLE IF EXISTS new_mediatags;"); -- just in case but not really required
            database.execSQL("CREATE TABLE new_mediatags (the_column_definitions_you_want)");
            //Copy existing data into the new table (if required)
            database.execSQL("INSERT INTO new_mediatags SELECT the_columns_you_are keeping,null;");
            //Rename the original table
            database.execSQL("ALTER TABLE mediatags RENAME TO old_mediatags;");
            //Rename the new table to the original name
            database.execSQL("ALTER TABLE new_mediatags RENAME TO mediatags;");
            //Drop the renamed original table
            database.execSQL("DROP TABLE IF EXISTS old_mediatags;");
    }
};

This assumes that you want to keep the existing data, if not then simply don't copy the data.

As an example consider the following :-

-- Create the original and load with some data
DROP TABLE If EXISTS mediatags;
CREATE TABLE IF NOT EXISTS mediatags (col1, col2, col3);
INSERT INTO mediatags VALUES('A','B','C'),('D','E','F');
SELECT * FROM mediatags;

-- The code that would be used
DROP TABLE IF EXISTS new_mediatags;
CREATE TABLE IF NOT EXISTS new_mediatags (col1, col3, col4); -- note no col2 but new col added as col4
INSERT INTO new_mediatags SELECT col1,col3,null FROM mediatags; -- copy existing data
ALTER TABLE mediatags RENAME TO old_mediatags;
ALTER TABLE new_mediatags RENAME TO mediatags;
DROP TABLE old_mediatags;

SELECT * FROM mediatags; -- output the data for the demo

The first 4 lines just create the original table, load it with some data and outpts the data as per :-

The other lines, swap the original table for the new table, removing col2 and adding col4, copying the existing data (the new column will be null although a value could be supplied) and finally for the demo outputs the data in the changed table as per :-


问:
Game of two stacks (hackers rank problem) algorithm
I was solving problem for game of two stacks on Hackers rank and got stuck.
Problem is my solution is not working when stack count is very huge (millions of entries)

https://www.hackerrank.com/challenges/game-of-two-stacks

Alexa has two stacks of non-negative integers, stack A and stack B where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game:

In each move, Nick can remove one integer from the top of either stack A or B stack.

Nick keeps a running sum of the integers he removes from the two stacks.

Nick is disqualified from the game if, at any point, his running sum becomes greater than some integer X given at the beginning of the game.

Nick's final score is the total number of integers he has removed from the two stacks.

find the maximum possible score Nick can achieve (i.e., the maximum number of integers he can remove without being disqualified) during each game and print it on a new line.

For each of the games, print an integer on a new line denoting the maximum possible score Nick can achieve without being disqualified.

Sample Input 0

```<code>1 -> Number of games
10 -> sum should not exceed 10
4 2 4 6 1  -> Stack A
2 1 8 5 -> Stack B
</code>```

Sample Output

```<code>4
</code>```

Below is my solution

```<code>def twoStacks(x, a, b):
a_list = []
sum_list = 0
for i in range(len(a)):
    sum_list = sum_list + a[i]
    if sum_list <= x:
        a_list.append(a[i])
    else:
        break

print(a_list)

print(a[i])
print(sum_list)
max_first = len(a_list)
replacement_list = []

list_a_length = len(a_list)
list_replacement_length = len(replacement_list)
list_b_length = len(b)
replacement_list_sum = 0
a_list_sum = sum(a_list)
while True:
    max_first = max(max_first, list_a_length + list_replacement_length)

    #print("max final is ",max_first)
    #print(sum(replacement_list))
    #print(sum(a_list))
    #print(b[0])
    #print(type(replacement_list), type(a_list), type(b))
    #print("sum of a lis is", sum(a_list))
    if list_b_length == 0:
        break
    elif replacement_list_sum + a_list_sum + b[0] <= x:
        #print(b[0])
        replacement_list_sum = replacement_list_sum + b[0]
        replacement_list.append(b.pop(0))
        list_replacement_length += 1
        list_b_length -= 1
        if replacement_list_sum  > x:
            break
    elif a_list:
        a_list_sum = a_list_sum - a_list[-1]
        a_list.pop()
        list_a_length -= 1
        #print(a_list)
    else:
        break
# print(replacement_list)
# print(a_list)
return max_first
</code>```

Where a is the first stack , b is second stack and x is sum in range of (1000000000)

Problem is my code is giving correct results but for large number it takes ages to give the output. any better solution is appreciated

Edit:

I changed my code and still taking ages

答:
I could see that you are not exiting the initial for loop once you met the criteria. You are going through the entire list even after the criteria is met, which can be avoided.
Try to break out of the loop once the criteria is met.

```<code> for i in range(len(a)):
        sum_list = sum_list + a[i]
        if sum_list <= x:
            a_list.append(a[i])
        else:
            break
</code>```

This would definitely improve the performance in case of a large number of values for list a.

Body:
I was solving problem for game of two stacks on Hackers rank and got stuck.
Problem is my solution is not working when stack count is very huge (millions of entries)

https://www.hackerrank.com/challenges/game-of-two-stacks

Alexa has two stacks of non-negative integers, stack A and stack B where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game:

In each move, Nick can remove one integer from the top of either stack A or B stack.

Nick keeps a running sum of the integers he removes from the two stacks.

Nick is disqualified from the game if, at any point, his running sum becomes greater than some integer X given at the beginning of the game.

Nick's final score is the total number of integers he has removed from the two stacks.

find the maximum possible score Nick can achieve (i.e., the maximum number of integers he can remove without being disqualified) during each game and print it on a new line.

For each of the games, print an integer on a new line denoting the maximum possible score Nick can achieve without being disqualified.

Sample Input 0

1 -> Number of games
10 -> sum should not exceed 10
4 2 4 6 1  -> Stack A
2 1 8 5 -> Stack B

Sample Output

4

Below is my solution

def twoStacks(x, a, b):
a_list = []
sum_list = 0
for i in range(len(a)):
    sum_list = sum_list + a[i]
    if sum_list <= x:
        a_list.append(a[i])
    else:
        break

print(a_list)

print(a[i])
print(sum_list)
max_first = len(a_list)
replacement_list = []

list_a_length = len(a_list)
list_replacement_length = len(replacement_list)
list_b_length = len(b)
replacement_list_sum = 0
a_list_sum = sum(a_list)
while True:
    max_first = max(max_first, list_a_length + list_replacement_length)

    #print("max final is ",max_first)
    #print(sum(replacement_list))
    #print(sum(a_list))
    #print(b[0])
    #print(type(replacement_list), type(a_list), type(b))
    #print("sum of a lis is", sum(a_list))
    if list_b_length == 0:
        break
    elif replacement_list_sum + a_list_sum + b[0] <= x:
        #print(b[0])
        replacement_list_sum = replacement_list_sum + b[0]
        replacement_list.append(b.pop(0))
        list_replacement_length += 1
        list_b_length -= 1
        if replacement_list_sum  > x:
            break
    elif a_list:
        a_list_sum = a_list_sum - a_list[-1]
        a_list.pop()
        list_a_length -= 1
        #print(a_list)
    else:
        break
# print(replacement_list)
# print(a_list)
return max_first

Where a is the first stack , b is second stack and x is sum in range of (1000000000)

Problem is my code is giving correct results but for large number it takes ages to give the output. any better solution is appreciated

Edit:

I changed my code and still taking ages

Body:
I could see that you are not exiting the initial for loop once you met the criteria. You are going through the entire list even after the criteria is met, which can be avoided.
Try to break out of the loop once the criteria is met.

 for i in range(len(a)):
        sum_list = sum_list + a[i]
        if sum_list <= x:
            a_list.append(a[i])
        else:
            break

This would definitely improve the performance in case of a large number of values for list a.


答:
Initial observations:

a) The order Nick picks the solution does not matter.If S = { a1, b1,a2,b2,... } you can reorder this and pick everyone from A first, then pick B.

b) If you have a solution S = S_A + S_B , consisting of S_A elements of A and S_B elements of B. You can rephrase the solution as "Some elements S_A of A" + " as many elements as possible from B given S_A ".

Suggested pseudo code:

1) Iterate through stack A.  Keep the cumulative sum.

2) For each step through A, check how many elements you can pick from B.

Optimization if necessary:
You can create all cumulative sums from B, and for each partial solution from A do a binary search on this sum table to quickly determine how many elements you can grab from B.

Here is an implementaion of the suggested idea, it solves the hackerrank problem, so its kinda cheating for you if you use it :-) :

```<code>from itertools import accumulate
import bisect

def twoStacks(x,a,b):
    cum_sum_b = list(accumulate(b))
    cum_sum_a = [0]+list(accumulate(a))
    return max( bisect.bisect_right(cum_sum_b, x-a_sum ) +i for i, a_sum in enumerate(cum_sum_a) if a_sum <= x)
</code>```

Title: Game of two stacks (hackers rank problem) algorithm

Body:
Initial observations:

a) The order Nick picks the solution does not matter.If S = { a1, b1,a2,b2,... } you can reorder this and pick everyone from A first, then pick B.

b) If you have a solution S = S_A + S_B , consisting of S_A elements of A and S_B elements of B. You can rephrase the solution as "Some elements S_A of A" + " as many elements as possible from B given S_A ".

Suggested pseudo code:

1) Iterate through stack A.  Keep the cumulative sum.

2) For each step through A, check how many elements you can pick from B.

Optimization if necessary:
You can create all cumulative sums from B, and for each partial solution from A do a binary search on this sum table to quickly determine how many elements you can grab from B.

Here is an implementaion of the suggested idea, it solves the hackerrank problem, so its kinda cheating for you if you use it :-) :

from itertools import accumulate
import bisect

def twoStacks(x,a,b):
    cum_sum_b = list(accumulate(b))
    cum_sum_a = [0]+list(accumulate(a))
    return max( bisect.bisect_right(cum_sum_b, x-a_sum ) +i for i, a_sum in enumerate(cum_sum_a) if a_sum <= x)


问:
keras pad_sequence for string data type
I have a list of sentences. I want to add padding to them; but when I use keras pad_sequence like this:

```<code>from keras.preprocessing.sequence import pad_sequences
s = [["this", "is", "a", "book"], ["this", "is", "not"]]
g = pad_sequences(s, dtype='str', maxlen=10, value='_PAD_')
</code>```

the result is:

```<code>array([['_', '_', '_', '_', '_', '_', 't', 'i', 'a', 'b'],
       ['_', '_', '_', '_', '_', '_', '_', 't', 'i', 'n']], dtype='<U1')
</code>```

Why it is not working properly?

I want to use this result as the input to the ELMO embedding and I need string sentences not integer encoding.

答:
The text should be first converted into numeric values. Keras provides tokenizer and two methods fit_on_texts and texts_to_sequences to work with text data.

Refer this keras documentation here

Tokenizer : This helps in vectorizing a text corpus, by turning each
    text into either a sequence of integers (each integer being the index
    of a token in a dictionary) or into a vector where the coefficient
    for each token could be binary, based on word count

fit_on_texts: This creates vocabulary index which is based on word frequency.

texts_to_sequences: This transforms each text in texts to a sequence of integers.

```<code>from keras.preprocessing import text, sequence
s = ["this", "is", "a", "book", "of my choice"]
tokenizer = text.Tokenizer(num_words=100,lower=True)
tokenizer.fit_on_texts(s)
seq_token = tokenizer.texts_to_sequences(s)
g = sequence.pad_sequences(seq_token, maxlen=10)
g
</code>```

Output

```<code>array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 2],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 3],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 4],
       [0, 0, 0, 0, 0, 0, 0, 5, 6, 7]], dtype=int32)
</code>```

Title: keras pad_sequence for string data type

Body:
I have a list of sentences. I want to add padding to them; but when I use keras pad_sequence like this:

from keras.preprocessing.sequence import pad_sequences
s = [["this", "is", "a", "book"], ["this", "is", "not"]]
g = pad_sequences(s, dtype='str', maxlen=10, value='_PAD_')

the result is:

array([['_', '_', '_', '_', '_', '_', 't', 'i', 'a', 'b'],
       ['_', '_', '_', '_', '_', '_', '_', 't', 'i', 'n']], dtype='<U1')

Why it is not working properly?

I want to use this result as the input to the ELMO embedding and I need string sentences not integer encoding.

Body:
The text should be first converted into numeric values. Keras provides tokenizer and two methods fit_on_texts and texts_to_sequences to work with text data.

Refer this keras documentation here

Tokenizer : This helps in vectorizing a text corpus, by turning each
    text into either a sequence of integers (each integer being the index
    of a token in a dictionary) or into a vector where the coefficient
    for each token could be binary, based on word count

fit_on_texts: This creates vocabulary index which is based on word frequency.

texts_to_sequences: This transforms each text in texts to a sequence of integers.

from keras.preprocessing import text, sequence
s = ["this", "is", "a", "book", "of my choice"]
tokenizer = text.Tokenizer(num_words=100,lower=True)
tokenizer.fit_on_texts(s)
seq_token = tokenizer.texts_to_sequences(s)
g = sequence.pad_sequences(seq_token, maxlen=10)
g

Output

array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 2],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 3],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 4],
       [0, 0, 0, 0, 0, 0, 0, 5, 6, 7]], dtype=int32)


问:
:app:transformClassesAndResourcesWithProguardForRelease takes too long
I have a problem with building release app with Proguard enabled. Building is stuck with executing the task :app:transformClassesAndResourcesWithProguardForRelease which takes for more than 40 minutes!

```<code>dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile('com.github.afollestad.material-dialogs:core:0.8.5.5@aar') {
        transitive = true
    }
    apt 'com.jakewharton:butterknife-compiler:8.0.1'
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile 'com.android.support:design:24.2.0'
    compile 'com.android.support:support-v4:24.2.0'
    compile 'com.android.support:percent:24.2.0'
    compile 'com.android.support:recyclerview-v7:24.2.0'
    compile 'com.android.support:cardview-v7:24.2.0'
    compile 'com.google.android.gms:play-services-appindexing:9.4.0'
    compile 'com.google.android.gms:play-services-analytics:9.4.0'
    compile 'com.instabug.library:instabug:2.6.1'
    compile 'net.hockeyapp.android:HockeySDK:4.1.0'
    compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
    compile 'com.squareup.okhttp:logging-interceptor:2.6.0'
    compile 'de.greenrobot:eventbus:2.4.0'
    compile 'com.jakewharton:butterknife:8.0.1'
    compile 'com.mobsandgeeks:android-saripaar:2.0.3'
    compile 'uk.co.chrisjenx:calligraphy:2.1.0'
    compile 'joda-time:joda-time:2.8.2'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'info.hoang8f:android-segmented:1.0.6'
    compile 'com.pnikosis:materialish-progress:1.7'
    compile 'hanks.xyz:smallbang-library:0.1.2'
    compile 'com.jzxiang.pickerview:TimePickerDialog:1.0.1'
}
</code>```

What can be the cause of this mess?

Thanks!

答:
In my case, it happens for proguard-rules.pro so I hide all the rule and use this configuration on my build.gradle file and it's works for me.

```<code>buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

defaultConfig {
    multiDexEnabled true
}

dexOptions {
    javaMaxHeapSize "4g"
}
</code>```

Body:
I have a problem with building release app with Proguard enabled. Building is stuck with executing the task :app:transformClassesAndResourcesWithProguardForRelease which takes for more than 40 minutes!

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile('com.github.afollestad.material-dialogs:core:0.8.5.5@aar') {
        transitive = true
    }
    apt 'com.jakewharton:butterknife-compiler:8.0.1'
    compile 'com.android.support:appcompat-v7:24.2.0'
    compile 'com.android.support:design:24.2.0'
    compile 'com.android.support:support-v4:24.2.0'
    compile 'com.android.support:percent:24.2.0'
    compile 'com.android.support:recyclerview-v7:24.2.0'
    compile 'com.android.support:cardview-v7:24.2.0'
    compile 'com.google.android.gms:play-services-appindexing:9.4.0'
    compile 'com.google.android.gms:play-services-analytics:9.4.0'
    compile 'com.instabug.library:instabug:2.6.1'
    compile 'net.hockeyapp.android:HockeySDK:4.1.0'
    compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
    compile 'com.squareup.okhttp:logging-interceptor:2.6.0'
    compile 'de.greenrobot:eventbus:2.4.0'
    compile 'com.jakewharton:butterknife:8.0.1'
    compile 'com.mobsandgeeks:android-saripaar:2.0.3'
    compile 'uk.co.chrisjenx:calligraphy:2.1.0'
    compile 'joda-time:joda-time:2.8.2'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'info.hoang8f:android-segmented:1.0.6'
    compile 'com.pnikosis:materialish-progress:1.7'
    compile 'hanks.xyz:smallbang-library:0.1.2'
    compile 'com.jzxiang.pickerview:TimePickerDialog:1.0.1'
}

What can be the cause of this mess?

Thanks!

Body:
In my case, it happens for proguard-rules.pro so I hide all the rule and use this configuration on my build.gradle file and it's works for me.

buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

defaultConfig {
    multiDexEnabled true
}

dexOptions {
    javaMaxHeapSize "4g"
}


问:
Flutter: Disable Swipe to Navigate Back in iOS and Android
I'm new to flutter development, and find it a bit frustrating in iOS when you have a navigation drawer and when you swipe to open it, it'll perform a Navigation.of(context).pop(). I would like to disable this "swipe to pop" behavior in iOS. I have been perusing the documentation, but without much luck.

I do see something referred to as a WillPopScope which seems to do the trick (github issue for it here), but I'm not 100% sure if this is the "correct" way to do it (it seems too complicated... it should be easier... like a setting on the root app).

答:
I have one additional point here. I was just solving this problem, but I also needed my user to be able to go back by pressing the "native" back button on the AppBar (did not want to reimplement AppBar just because of this), and I found this niche little flag: userGestureInProgress on the Navigator object, so what I use (and presume is the preferred way) is:

```<code>onWillPop: () async {
    if (Navigator.of(context).userGestureInProgress)
      return false;
    else
      return true;
  },
</code>```

Body:
I have one additional point here. I was just solving this problem, but I also needed my user to be able to go back by pressing the "native" back button on the AppBar (did not want to reimplement AppBar just because of this), and I found this niche little flag: userGestureInProgress on the Navigator object, so what I use (and presume is the preferred way) is:

onWillPop: () async {
    if (Navigator.of(context).userGestureInProgress)
      return false;
    else
      return true;
  },


问:
Unexpected output when querying joint tables in sequelize js
I am trying to query records from two tables which have a one to many relationship using the following code using sequelize.
In this case one author can have many books while a book can be authored by only one author.

```<code>const BookList = await Book.findAll({
  include: [
    {
      model: Author,
      attributes: ['name'],
    },
  ],
  raw: true,
});
</code>```

Books Model

```<code>const Books = sequelize.define(
  'books',
  {
    id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
    },
    name: {
      type: DataTypes.STRING(255),
      allowNull: false,
    },
    author_id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      references: {
        model: 'authors',
        key: 'id',
      },
    },
  },
  {
    tableName: 'books',
  },
);
</code>```

Authors Model

```<code>const Authors = sequelize.define(
  'authors',
  {
    id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
    },
    name: {
      type: DataTypes.STRING(255),
      allowNull: false,
    },
  },
  {
    tableName: 'authors',
  },
);
</code>```

The expected outcome would be something as follows.

```<code>[
  {
    id: 1,
    name: "book1",
    author_id: 1,
    author: {
      name: "tom",
    }
  },
  .....
]
</code>```

However the outcome i am getting is as follows.

```<code>[
  {
    id: 1,
    name: "book1",
    author_id: 1,
    "author.name": "tom"
  },
  .....
]
</code>```

My question would by why am i getting "author.name" instead of an author object as shown in many of the examples on the sequelize docs.

答:
So, when you use raw: true you will receive the brut data  without any format and it's not bind to any model definition.

If you want sequelize to format the different (using dottie.js under the hood) objects you can use the property nest: true

```<code>const BookList = await Book.findAll({
  include: [
      {
        model: Author,
        attributes: ['name'],
      },
  ],
  raw: true,
  nest: true
});
</code>```

Here the link to the documentation: http://docs.sequelizejs.com/class/lib/sequelize.js~Sequelize.html

Body:
I am trying to query records from two tables which have a one to many relationship using the following code using sequelize.
In this case one author can have many books while a book can be authored by only one author.

const BookList = await Book.findAll({
  include: [
    {
      model: Author,
      attributes: ['name'],
    },
  ],
  raw: true,
});

Books Model

const Books = sequelize.define(
  'books',
  {
    id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
    },
    name: {
      type: DataTypes.STRING(255),
      allowNull: false,
    },
    author_id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      references: {
        model: 'authors',
        key: 'id',
      },
    },
  },
  {
    tableName: 'books',
  },
);

Authors Model

const Authors = sequelize.define(
  'authors',
  {
    id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
    },
    name: {
      type: DataTypes.STRING(255),
      allowNull: false,
    },
  },
  {
    tableName: 'authors',
  },
);

The expected outcome would be something as follows.

[
  {
    id: 1,
    name: "book1",
    author_id: 1,
    author: {
      name: "tom",
    }
  },
  .....
]

However the outcome i am getting is as follows.

[
  {
    id: 1,
    name: "book1",
    author_id: 1,
    "author.name": "tom"
  },
  .....
]

My question would by why am i getting "author.name" instead of an author object as shown in many of the examples on the sequelize docs.

Body:
So, when you use raw: true you will receive the brut data  without any format and it's not bind to any model definition.

If you want sequelize to format the different (using dottie.js under the hood) objects you can use the property nest: true

const BookList = await Book.findAll({
  include: [
      {
        model: Author,
        attributes: ['name'],
      },
  ],
  raw: true,
  nest: true
});

Here the link to the documentation: http://docs.sequelizejs.com/class/lib/sequelize.js~Sequelize.html


问:
Get the text box value from the UI-Grid onblur
I would like to get the value that is entered in the textbox on blur event in UI-Grid.
iam unable to get the value the event is getting triggered but unble to get the logic how to get the text box value.
can some help in figure it out.

This is the code:

```<code>  $scope.gridOptions = {
        headerTemplate: 'header-template.html',
        showColumnFooter: true,
        columnDefs: [{ name: 'H', width: '15%' }, { name: 'H1', width: '30%' }],
        data: [
            { H: "", H1: "Brand name" },
            { H: " ", H1: "Molecule" },
            { H: "Product Details ", H1: "Therapeutic area" },
            { H: " ", H1: "Targeted indication " },
            { H: " ", H1: "Estimated size of the patient population (in your market) " }
        ],
        onRegisterApi: function (gridApi) {
            $scope.gridApi = gridApi;
            gridApi.core.on.renderingComplete(gridDrawn());
        },
    };

 $scope.gridOptions.columnDefs.push({
            name: 'H2', enableCellEdit: false,
            field: "colButton", displayName: "Push Me",
            //aggregationType: uiGridConstants.aggregationTypes.sum,
            aggregationHideLabel: true,
            cellTemplate: '<div><input type="Number" placeholder="Enter Number" onblur="calculateTotal()" style="width:90%" /></div>',
            rowTemplate: '<div>Hai</div>',
            width: '10%',
            footerCellTemplate: '<div class="ui-grid-cell-contents" >Total: {{col.getAggregationValue() | number:2 }}</div>'
        });

function calculateTotal() {
    alert("Hello");
 gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
            $scope.msg.lastCellEdited = 'edited row id:' + rowEntity.id + ' Column:' + colDef.name + ' newValue:' + newValue + ' oldValue:' + oldValue;
            $scope.$apply();
        });
}
</code>```

答:
define a variable on scope like:-

```<code>$scope.textboxValue = '';
</code>```

then add the variable to the ng-model of the cell template like below

```<code>cellTemplate: '<div><input type="Number" ng-model="textboxValue" placeholder="Enter Number" onblur="calculateTotal()" style="width:90%" /></div>'
</code>```

your textbox value will be accessible in the function

```<code>$scope.calculateTotal = function () {

    console.log($scope.textboxValue);
    //other code
}
</code>```

Body:
I would like to get the value that is entered in the textbox on blur event in UI-Grid.
iam unable to get the value the event is getting triggered but unble to get the logic how to get the text box value.
can some help in figure it out.

This is the code:

  $scope.gridOptions = {
        headerTemplate: 'header-template.html',
        showColumnFooter: true,
        columnDefs: [{ name: 'H', width: '15%' }, { name: 'H1', width: '30%' }],
        data: [
            { H: "", H1: "Brand name" },
            { H: " ", H1: "Molecule" },
            { H: "Product Details ", H1: "Therapeutic area" },
            { H: " ", H1: "Targeted indication " },
            { H: " ", H1: "Estimated size of the patient population (in your market) " }
        ],
        onRegisterApi: function (gridApi) {
            $scope.gridApi = gridApi;
            gridApi.core.on.renderingComplete(gridDrawn());
        },
    };

 $scope.gridOptions.columnDefs.push({
            name: 'H2', enableCellEdit: false,
            field: "colButton", displayName: "Push Me",
            //aggregationType: uiGridConstants.aggregationTypes.sum,
            aggregationHideLabel: true,
            cellTemplate: '
<input type="Number" placeholder="Enter Number" onblur="calculateTotal()" style="width:90%" />
',
            rowTemplate: '
Hai
',
            width: '10%',
            footerCellTemplate: '
Total: {{col.getAggregationValue() | number:2 }}
'
        });

function calculateTotal() {
    alert("Hello");
 gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
            $scope.msg.lastCellEdited = 'edited row id:' + rowEntity.id + ' Column:' + colDef.name + ' newValue:' + newValue + ' oldValue:' + oldValue;
            $scope.$apply();
        });
}

Body:
define a variable on scope like:-

$scope.textboxValue = '';

then add the variable to the ng-model of the cell template like below

cellTemplate: '<div><input type="Number" ng-model="textboxValue" placeholder="Enter Number" onblur="calculateTotal()" style="width:90%" /></div>'

your textbox value will be accessible in the function

$scope.calculateTotal = function () {

    console.log($scope.textboxValue);
    //other code
}


问:
Styling Google Maps InfoWindow
I've been attempting to style my Google Maps InfoWindow, but the documentation is very limited on this topic. How do you style an InfoWindow?

答:
Google wrote some code to assist with this. Here are some examples: Example using InfoBubble, Styled markers and Info Window Custom (using OverlayView).

The code in the links above take different routes to achieve similar results. The gist of it is that it is not easy to style InfoWindows directly, and it might be easier to use the additional InfoBubble class instead of InfoWindow, or to override GOverlay. Another option would be to modify the elements of the InfoWindow using javascript (or jQuery), like later ATOzTOA suggested.

Possibly the simplest of these examples is using InfoBubble instead of InfoWindow. InfoBubble is available by importing this file (which you should host yourself): http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobubble/src/infobubble.js

InfoBubble's Github project page.

InfoBubble is very stylable, compared to InfoWindow:

```<code> infoBubble = new InfoBubble({
      map: map,
      content: '<div class="mylabel">The label</div>',
      position: new google.maps.LatLng(-32.0, 149.0),
      shadowStyle: 1,
      padding: 0,
      backgroundColor: 'rgb(57,57,57)',
      borderRadius: 5,
      arrowSize: 10,
      borderWidth: 1,
      borderColor: '#2c2c2c',
      disableAutoPan: true,
      hideCloseButton: true,
      arrowPosition: 30,
      backgroundClassName: 'transparent',
      arrowStyle: 2
});

infoBubble.open();
</code>```

You can also call it with a given map and marker to open on:

```<code>infoBubble.open(map, marker);
</code>```

As another example, the Info Window Custom example extends the GOverlay class from the Google Maps API and uses this as a base for creating a more flexible info window. It first creates the class:

```<code>/* An InfoBox is like an info window, but it displays
 * under the marker, opens quicker, and has flexible styling.
 * @param {GLatLng} latlng Point to place bar at
 * @param {Map} map The map on which to display this InfoBox.
 * @param {Object} opts Passes configuration options - content,
 *   offsetVertical, offsetHorizontal, className, height, width
 */
function InfoBox(opts) {
  google.maps.OverlayView.call(this);
  this.latlng_ = opts.latlng;
  this.map_ = opts.map;
  this.offsetVertical_ = -195;
  this.offsetHorizontal_ = 0;
  this.height_ = 165;
  this.width_ = 266;

  var me = this;
  this.boundsChangedListener_ =
    google.maps.event.addListener(this.map_, "bounds_changed", function() {
      return me.panMap.apply(me);
    });

  // Once the properties of this OverlayView are initialized, set its map so
  // that we can display it.  This will trigger calls to panes_changed and
  // draw.
  this.setMap(this.map_);
}
</code>```

after which it proceeds to override GOverlay:

```<code>InfoBox.prototype = new google.maps.OverlayView();
</code>```

You should then override the methods you need: createElement, draw, remove and panMap. It gets rather involved, but in theory you are just drawing a div on the map yourself now, instead of using a normal Info Window.

Title: Styling Google Maps InfoWindow

Body:
Google wrote some code to assist with this. Here are some examples: Example using InfoBubble, Styled markers and Info Window Custom (using OverlayView).

The code in the links above take different routes to achieve similar results. The gist of it is that it is not easy to style InfoWindows directly, and it might be easier to use the additional InfoBubble class instead of InfoWindow, or to override GOverlay. Another option would be to modify the elements of the InfoWindow using javascript (or jQuery), like later ATOzTOA suggested.

Possibly the simplest of these examples is using InfoBubble instead of InfoWindow. InfoBubble is available by importing this file (which you should host yourself): http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobubble/src/infobubble.js

InfoBubble's Github project page.

InfoBubble is very stylable, compared to InfoWindow:

 infoBubble = new InfoBubble({
      map: map,
      content: '<div class="mylabel">The label</div>',
      position: new google.maps.LatLng(-32.0, 149.0),
      shadowStyle: 1,
      padding: 0,
      backgroundColor: 'rgb(57,57,57)',
      borderRadius: 5,
      arrowSize: 10,
      borderWidth: 1,
      borderColor: '#2c2c2c',
      disableAutoPan: true,
      hideCloseButton: true,
      arrowPosition: 30,
      backgroundClassName: 'transparent',
      arrowStyle: 2
});

infoBubble.open();

You can also call it with a given map and marker to open on:

infoBubble.open(map, marker);

As another example, the Info Window Custom example extends the GOverlay class from the Google Maps API and uses this as a base for creating a more flexible info window. It first creates the class:

/* An InfoBox is like an info window, but it displays
 * under the marker, opens quicker, and has flexible styling.
 * @param {GLatLng} latlng Point to place bar at
 * @param {Map} map The map on which to display this InfoBox.
 * @param {Object} opts Passes configuration options - content,
 *   offsetVertical, offsetHorizontal, className, height, width
 */
function InfoBox(opts) {
  google.maps.OverlayView.call(this);
  this.latlng_ = opts.latlng;
  this.map_ = opts.map;
  this.offsetVertical_ = -195;
  this.offsetHorizontal_ = 0;
  this.height_ = 165;
  this.width_ = 266;

  var me = this;
  this.boundsChangedListener_ =
    google.maps.event.addListener(this.map_, "bounds_changed", function() {
      return me.panMap.apply(me);
    });

  // Once the properties of this OverlayView are initialized, set its map so
  // that we can display it.  This will trigger calls to panes_changed and
  // draw.
  this.setMap(this.map_);
}

after which it proceeds to override GOverlay:

InfoBox.prototype = new google.maps.OverlayView();

You should then override the methods you need: createElement, draw, remove and panMap. It gets rather involved, but in theory you are just drawing a div on the map yourself now, instead of using a normal Info Window.