问:
How can I make add firepad to my reactjs project?
So I've been learning react, and wanted to make a basic firepad instance. My current setup is having one container div in my index.html, and having all of my react components rendering through that div. My current attempts and the code I'm showing with this have been in an environment with gulp and browserify, but I'm also playing around with ES6 and webpack. So I'm pretty flexible about getting this working as I learn. Here's the code:

```<code>"use strict"

var React = require('react')
  , Firebase = require('firebase')
  , fbRoot = 'myURL'
  , CodeMirror = require('codemirror')
  , Firepad = require('firepad')
  , firepadRef = new Firebase(fbRoot + 'session/')
  , myCodeMirror = CodeMirror(document.getElementById('firepad'), {lineWrapping: true})
  , myFirePad = Firepad.fromCodeMirror(firepadRef, myCodeMirror, { richTextShortcuts: true, richTextToolbar: true, defaultText: 'Hello, World!'});

var WritePage = React.createClass({
  render: function(){
    return (
      <div>
        <div id="firepad"></div>
      </div>
    );
  }
});

module.exports = WritePage;
</code>```

The first error I was getting was that it couldn't find the codemirror.js file. Although CodeMirror was being correctly defined in Chrome's dev tools, I moved that from requiring the npm package to just linking the 2 needed codemirror files to my html. It then gave me an error about not being able to take .replaceChild of undefined. I then tried moving all of the dependency files over to my index.html, but still had the same .replaceChild error. Anyone have any experience with react and firepad? I read in the reactfire docs that it's one way binding from firebase to my site, which for my case making a read-only firepad would be fine. Like I said, I'm flexible all of this stuff is new to me.

答:
Use these npm packages - brace, react-ace, firebase, firepad.

Since firepad needs aceto be present globally, assign brace to global var
like(not the best way, but works) before importing firepad

```<code>import firebase from 'firebase/app';
import 'firebase/database';
import brace from 'brace';
global.ace = brace;
global.ace.require = global.ace.acequire;
import Firepad from 'firepad';
</code>```

Use ref to get instance of ReactAce and initialize it in componentDidMount using:

```<code>new Firepad.fromACE(this.firepadRef, this.aceInstance.editor, options);
</code>```

Similarly for CodeMirror editor.

Hoping, this would be of some help.

Body:
So I've been learning react, and wanted to make a basic firepad instance. My current setup is having one container div in my index.html, and having all of my react components rendering through that div. My current attempts and the code I'm showing with this have been in an environment with gulp and browserify, but I'm also playing around with ES6 and webpack. So I'm pretty flexible about getting this working as I learn. Here's the code:

"use strict"

var React = require('react')
  , Firebase = require('firebase')
  , fbRoot = 'myURL'
  , CodeMirror = require('codemirror')
  , Firepad = require('firepad')
  , firepadRef = new Firebase(fbRoot + 'session/')
  , myCodeMirror = CodeMirror(document.getElementById('firepad'), {lineWrapping: true})
  , myFirePad = Firepad.fromCodeMirror(firepadRef, myCodeMirror, { richTextShortcuts: true, richTextToolbar: true, defaultText: 'Hello, World!'});

var WritePage = React.createClass({
  render: function(){
    return (

    );
  }
});

module.exports = WritePage;

The first error I was getting was that it couldn't find the codemirror.js file. Although CodeMirror was being correctly defined in Chrome's dev tools, I moved that from requiring the npm package to just linking the 2 needed codemirror files to my html. It then gave me an error about not being able to take .replaceChild of undefined. I then tried moving all of the dependency files over to my index.html, but still had the same .replaceChild error. Anyone have any experience with react and firepad? I read in the reactfire docs that it's one way binding from firebase to my site, which for my case making a read-only firepad would be fine. Like I said, I'm flexible all of this stuff is new to me.

Body:
Use these npm packages - brace, react-ace, firebase, firepad.

Since firepad needs aceto be present globally, assign brace to global var
like(not the best way, but works) before importing firepad

import firebase from 'firebase/app';
import 'firebase/database';
import brace from 'brace';
global.ace = brace;
global.ace.require = global.ace.acequire;
import Firepad from 'firepad';

Use ref to get instance of ReactAce and initialize it in componentDidMount using:

new Firepad.fromACE(this.firepadRef, this.aceInstance.editor, options);

Similarly for CodeMirror editor.

Hoping, this would be of some help.


来源: stackexchange

问:
How can I map dates in python using lambdas? I am trying to do this to print Excel sheet in Odoo
I am trying to map keys for Excel sheet using lambdas. But I can't map properly. Please help                  </p>

```<code>def _get_lines(self,cr,uid,ids,val, context=None):
    dict_dat = val
    od_start = dict_dat['od_start'][0]
    qry= ''
    x = 'hr_payslip.date_from = '+ date(od_start)
    print x
    qry = x
    qry_data = []
    qry = self.make_qry(cr,uid,ids,context=context)
    keys = self.get_keys()
    cr.execute(qry)
    qry_data = cr.fetchall()
    der_data = map(lambda x:dict(zip(keys,x)),qry_data)
    print der_data
    return der_data
</code>```

答:
```<code>x = 'hr_payslip.date_from = '+ str(val.get('od_start'))
</code>```

Solved the problem

ContentLicense: CC BY-SA 3.0

Body:
I am trying to map keys for Excel sheet using lambdas. But I can't map properly. Please help

def _get_lines(self,cr,uid,ids,val, context=None):
    dict_dat = val
    od_start = dict_dat['od_start'][0]
    qry= ''
    x = 'hr_payslip.date_from = '+ date(od_start)
    print x
    qry = x
    qry_data = []
    qry = self.make_qry(cr,uid,ids,context=context)
    keys = self.get_keys()
    cr.execute(qry)
    qry_data = cr.fetchall()
    der_data = map(lambda x:dict(zip(keys,x)),qry_data)
    print der_data
    return der_data

Body:
x = 'hr_payslip.date_from = '+ str(val.get('od_start'))

Solved the problem


问:
Worksheet_Calculate to hide command button
I found the code below for Worksheet_Change. But my H29 is formula =SUM.
How do I change this to Worksheet_Calculate so that the below macro will run?

Basically what I want is if H29 is calculated as being equal to 20, show the button, else hide it.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False

If Target = Range("H29") Then
If Target.Value = "20" Then
Me.CommandButton1.Visible = True

Else

Me.CommandButton1.Visible = False

End If
Application.ScreenUpdating = True
End If
</code>```

答:
Depending on the button type, the code to instruct the button will be different. Try this.</p>

```<code>Private Sub Worksheet_Calculate()
'ActiveX button
If Range("H29").Value = 20 Then
  Sheets("Sheet1").CommandButton2.Visible = False
Else
  Sheets("Sheet1").CommandButton2.Visible = True
End If

'Forms Button
If Range("H29").Value = 20 Then
  Sheets("Sheet1").Shapes("CommandButton1").Visible = msoFalse
Else
  Sheets("Sheet1").Shapes("CommandButton1").Visible = msoTrue
End If

End Sub
</code>```

Body:
I found the code below for Worksheet_Change. But my H29 is formula =SUM.
How do I change this to Worksheet_Calculate so that the below macro will run?

Basically what I want is if H29 is calculated as being equal to 20, show the button, else hide it.

Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False

If Target = Range("H29") Then
If Target.Value = "20" Then
Me.CommandButton1.Visible = True

Else

Me.CommandButton1.Visible = False

End If
Application.ScreenUpdating = True
End If

Body:
Depending on the button type, the code to instruct the button will be different. Try this.

Private Sub Worksheet_Calculate()
'ActiveX button
If Range("H29").Value = 20 Then
  Sheets("Sheet1").CommandButton2.Visible = False
Else
  Sheets("Sheet1").CommandButton2.Visible = True
End If

'Forms Button
If Range("H29").Value = 20 Then
  Sheets("Sheet1").Shapes("CommandButton1").Visible = msoFalse
Else
  Sheets("Sheet1").Shapes("CommandButton1").Visible = msoTrue
End If

End Sub


问:
cannot associate products and categories table in cakephp 3
I have a table structure:

products:

products_id

product_name

product_price

product_description

category_id

categories:

category_id

category_name

There are 2 different forms to add and edit products and categories respectively. I want to associate both the tables so that i do not have to search category_name based on the category_id in the edit form dropdown list.
I have tried associating it but i got following errors:

Table "Cake\ORM\Table" is not associated with "Categories"

```<code>class ProductsTable extends Table {
   public function initialize(array $config){
        $this->table('Products');
        $this->primaryKey('product_id');
       $this->belongsTo('Categories', ['foreignKey' => 'product_id']);

    }
}

class CategoriesTable extends Table {
  public function initialize(array $config){
     $this->table('Categories');
     $this->primaryKey('category_id');
      $this->hasMany('Products', ['foreignKey' => 'category_id']);
    }
}
</code>```

View:

```<code>  public function index()
    {
$this->set('categories', $this->Products->Categories->find('list', array('fields' => array('Categories.category_id'),'value'=>array('Categories.category_name'))));
}
</code>```

Please help to sort out my issue.

答:
change
$this->primaryKey('product_id');
to
 $this->primaryKey('products_id');

And add
$this->displayField('category_name');

Body:
I have a table structure:

products:

products_id

product_name

product_price

product_description

category_id

categories:

category_id

category_name

There are 2 different forms to add and edit products and categories respectively. I want to associate both the tables so that i do not have to search category_name based on the category_id in the edit form dropdown list.
I have tried associating it but i got following errors:

Table "Cake\ORM\Table" is not associated with "Categories"

class ProductsTable extends Table {
   public function initialize(array $config){
        $this->table('Products');
        $this->primaryKey('product_id');
       $this->belongsTo('Categories', ['foreignKey' => 'product_id']);

    }
}

class CategoriesTable extends Table {
  public function initialize(array $config){
     $this->table('Categories');
     $this->primaryKey('category_id');
      $this->hasMany('Products', ['foreignKey' => 'category_id']);
    }
}

View:

  public function index()
    {
$this->set('categories', $this->Products->Categories->find('list', array('fields' => array('Categories.category_id'),'value'=>array('Categories.category_name'))));
}

Please help to sort out my issue.


问:
splitting a data frame by date and computing median for all rows with each date
I am attempting to roughly estimate that amount of work than could have been done by staff for a given month.

I've got a csv that looks roughly like this (although it's a lot bigger):

```<code>+--------+-------+---------------+
|  Date  | Name  | Units of Work |
+--------+-------+---------------+
| 1/1/17 | Bob   |           450 |
| 2/1/17 | Alice |           300 |
| 2/1/17 | Bob   |           450 |
| 2/1/17 | Larry |            50 |
| 3/1/17 | Alice |           400 |
| 3/1/17 | Bob   |            11 |
| 3/1/17 | Larry |           100 |
| 4/1/17 | Alice |          1000 |
| 4/1/17 | Bob   |           240 |
| 4/1/17 | Larry |            33 |
+--------+-------+---------------+
</code>```

I want to:

Compute the median 'Units of work' for each 'Date'

Determine if any 'Name' did less than 20% of the median 'Units of work' for that 'Date'

Remove 'Name' if it did fewer than 20% of the median

Multiply the count of 'Name' left for the 'Date' by the median 'Units of work' for that 'Date'

Output a new csv that has each 'Date', appearing only once, on its own row, and that date's median 'Units of work' multiplied by the remaining 'Name' for that 'Date'

I can't even meet requirement 1, much less 2 through 5.  I'm getting one file for each date.  And instead of a column with the median, I get a new column called 'NewColumn' filled with the word 'median', like so:

```<code># -*- coding: utf-8 -*-
import pandas as pd
df = pd.read_csv('source.csv')
df = df.sort_values('date_trunc').assign(NewColumn='median')
df.median(axis=None, skipna=None, level=None, numeric_only=None)
for i, g in df.groupby('date_trunc'):
    g.to_csv('{}.csv'.format(i), header=True, index_label=False, index=False)
    +---------+-------+---------------+-----------+
    |  Date   | Name  | Units of work | NewColumn |
    +---------+-------+---------------+-----------+
    | 12/1/16 | Alice |          6222 | median    |
    | 12/1/16 | Bob   |         14530 | median    |
    | 12/1/16 | Larry |         16887 | median    |
    +---------+-------+---------------+-----------+
</code>```

I know I'm probably doing a lot wrong here, but I'd really appreciate some guidance.

What I want to end up with is a single csv with this:

```<code>+---------+--------+
|  Date   | Median |
+---------+--------+
| 12/1/16 |   1110 |
| 1/1/17  |   1400 |
| 2/1/17  |   1200 |
+---------+--------+
</code>```

答:
I hope the following steps get you closer to your desired CSV output.

First, here's a clean rendition of the input DataFrame for anyone else looking to copy-paste into pd.read_clipboard():

```<code>     Date     Name     Units of Work
0   Jan-17    Bob               450.0
1   Feb-17    Alice             300.0
2   Feb-17    Bob               450.0
3   Feb-17    Larry              50.0
4   Mar-17    Alice             400.0
5   Mar-17    Bob                11.0
6   Mar-17    Larry             100.0
7   Apr-17    Alice            1000.0
8   Apr-17    Bob               240.0
9   Apr-17    Larry              33.0
</code>```

0. Cast dates to python datetime (for sensible sort order)

```<code># Docs on Python datetime format strings: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
df['Date'] = pd.to_datetime(df['Date'].apply(lambda x: x.strip()), format='%b-%y')
</code>```

1. For each date, find the median units of work

```<code>meds = df.groupby('Date')[['Units of Work']].median()
meds
    Units of Work
Date
2017-01-01  450.0
2017-02-01  300.0
2017-03-01  100.0
2017-04-01  240.0
</code>```

2, 3. Drop rows where units of work < 20% of that date's median units of work

```<code># Set an index on which to merge the medians
df2 = df.set_index('Date')
# Pandas is smart enough to merge the 4-row meds DataFrame onto the 10-row df2 DataFrame based on matching index values
df2['Median'] = meds

# Build a boolean mask to pick out "hard workers" and "slackers"
mask = df2['Units of Work'] >= 0.2 * df2['Median']

# "Hard workers," where units of work >= 20% of that date's median
df2[mask]
               Name  Units of Work  Median
Date
2017-01-01   Bob             450.0   450.0
2017-02-01   Alice           300.0   300.0
2017-02-01   Bob             450.0   300.0
2017-03-01   Alice           400.0   100.0
2017-03-01   Larry           100.0   100.0
2017-04-01   Alice          1000.0   240.0
2017-04-01   Bob             240.0   240.0

# Bonus: "slackers," where units of work < 20% of that date's median
df2[~mask]
               Name  Units of Work  Median
Date
2017-02-01   Larry            50.0   300.0
2017-03-01   Bob              11.0   100.0
2017-04-01   Larry            33.0   240.0
</code>```

4. For each date, multiply the number of "hard workers" by the median units of work

```<code>df2[mask].groupby('Date').size().mul(meds['Units of Work'])
2017-01-01    450.0
2017-02-01    600.0
2017-03-01    200.0
2017-04-01    480.0
</code>```

Body:
I am attempting to roughly estimate that amount of work than could have been done by staff for a given month.

I've got a csv that looks roughly like this (although it's a lot bigger):

+--------+-------+---------------+
|  Date  | Name  | Units of Work |
+--------+-------+---------------+
| 1/1/17 | Bob   |           450 |
| 2/1/17 | Alice |           300 |
| 2/1/17 | Bob   |           450 |
| 2/1/17 | Larry |            50 |
| 3/1/17 | Alice |           400 |
| 3/1/17 | Bob   |            11 |
| 3/1/17 | Larry |           100 |
| 4/1/17 | Alice |          1000 |
| 4/1/17 | Bob   |           240 |
| 4/1/17 | Larry |            33 |
+--------+-------+---------------+

I want to:

Compute the median 'Units of work' for each 'Date'

Determine if any 'Name' did less than 20% of the median 'Units of work' for that 'Date'

Remove 'Name' if it did fewer than 20% of the median

Multiply the count of 'Name' left for the 'Date' by the median 'Units of work' for that 'Date'

Output a new csv that has each 'Date', appearing only once, on its own row, and that date's median 'Units of work' multiplied by the remaining 'Name' for that 'Date'

I can't even meet requirement 1, much less 2 through 5.  I'm getting one file for each date.  And instead of a column with the median, I get a new column called 'NewColumn' filled with the word 'median', like so:

# -*- coding: utf-8 -*-
import pandas as pd
df = pd.read_csv('source.csv')
df = df.sort_values('date_trunc').assign(NewColumn='median')
df.median(axis=None, skipna=None, level=None, numeric_only=None)
for i, g in df.groupby('date_trunc'):
    g.to_csv('{}.csv'.format(i), header=True, index_label=False, index=False)
    +---------+-------+---------------+-----------+
    |  Date   | Name  | Units of work | NewColumn |
    +---------+-------+---------------+-----------+
    | 12/1/16 | Alice |          6222 | median    |
    | 12/1/16 | Bob   |         14530 | median    |
    | 12/1/16 | Larry |         16887 | median    |
    +---------+-------+---------------+-----------+

I know I'm probably doing a lot wrong here, but I'd really appreciate some guidance.

What I want to end up with is a single csv with this:

+---------+--------+
|  Date   | Median |
+---------+--------+
| 12/1/16 |   1110 |
| 1/1/17  |   1400 |
| 2/1/17  |   1200 |
+---------+--------+

Body:
I hope the following steps get you closer to your desired CSV output.

First, here's a clean rendition of the input DataFrame for anyone else looking to copy-paste into pd.read_clipboard():

     Date     Name     Units of Work
0   Jan-17    Bob               450.0
1   Feb-17    Alice             300.0
2   Feb-17    Bob               450.0
3   Feb-17    Larry              50.0
4   Mar-17    Alice             400.0
5   Mar-17    Bob                11.0
6   Mar-17    Larry             100.0
7   Apr-17    Alice            1000.0
8   Apr-17    Bob               240.0
9   Apr-17    Larry              33.0

0. Cast dates to python datetime (for sensible sort order)

# Docs on Python datetime format strings: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
df['Date'] = pd.to_datetime(df['Date'].apply(lambda x: x.strip()), format='%b-%y')

1. For each date, find the median units of work

meds = df.groupby('Date')[['Units of Work']].median()
meds
    Units of Work
Date
2017-01-01  450.0
2017-02-01  300.0
2017-03-01  100.0
2017-04-01  240.0

2, 3. Drop rows where units of work < 20% of that date's median units of work

# Set an index on which to merge the medians
df2 = df.set_index('Date')
# Pandas is smart enough to merge the 4-row meds DataFrame onto the 10-row df2 DataFrame based on matching index values
df2['Median'] = meds

# Build a boolean mask to pick out "hard workers" and "slackers"
mask = df2['Units of Work'] >= 0.2 * df2['Median']

# "Hard workers," where units of work >= 20% of that date's median
df2[mask]
               Name  Units of Work  Median
Date
2017-01-01   Bob             450.0   450.0
2017-02-01   Alice           300.0   300.0
2017-02-01   Bob             450.0   300.0
2017-03-01   Alice           400.0   100.0
2017-03-01   Larry           100.0   100.0
2017-04-01   Alice          1000.0   240.0
2017-04-01   Bob             240.0   240.0

# Bonus: "slackers," where units of work < 20% of that date's median
df2[~mask]
               Name  Units of Work  Median
Date
2017-02-01   Larry            50.0   300.0
2017-03-01   Bob              11.0   100.0
2017-04-01   Larry            33.0   240.0

4. For each date, multiply the number of "hard workers" by the median units of work

df2[mask].groupby('Date').size().mul(meds['Units of Work'])
2017-01-01    450.0
2017-02-01    600.0
2017-03-01    200.0
2017-04-01    480.0


问:
How to drop all tables and reset an Azure SQL Database
I have an ASP.NET MVC 5 project that works local and whenever I need to blow away the DB, I just open a new query on it, change the available database dropdown to master, then close the connection on my local db and run the query "drop database [name]".  Then I build the project, go into the package manager console and run "Update-Database". This seems to rebuild a fresh local database and runs the seed method in my configuration.cs file.

The problem is when I need to test things in a live environment so I can test API's and such better, I will do a deploy to an Azure Website and the accompanying Azure DB, which is nice and easy to do. I check off the "Execute code first migrations" in the publish wizard and most of the time it works and I can run and debug my live version. Sometimes I need to blow away that db and start from scratch again, but the only way I've really found to do it is to go into the Azure portal, delete the database, and then re-create it with the same name. This takes some time for Azure to process, so this is a slow testing cycle.

Is there a quick way to just drop/reset a Azure SQL DB to it's fresh, empty, virgin state and then re-publish with "execute code first migrations" to have it re-create the tables and re-seed the data?

I've seen some talk of creating an initial migration after I create the db, and then trying to use the Powershell to do some sort of roll-back to that initial state, but I haven't had luck getting it to work, and I want to delete all the data at the same time. Maybe I've just got the wrong syntax or haven't found a good enough tutorial. While I can run a query on the Azure DB to "drop database [x]" it literally kills the SQL Azure DB instance as you'd expect and you need to go back into the portal to recreate it. Sometimes that initial state is no good as the model has since been updated, so this may not be useful anyway.

I feel like there should be some easier quicker way to test changes on a live environment as there all these great tools and shortcuts provided by MS, but did they just drop the ball here for this phase of development or am I missing something?

答:
Azure SQL is essentially SQL server. So you can use MS SQL Server Management Studio https://learn.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms

Open the database in Management Studio using your admin account, then execute drop table SQL commands or use the GUI right click menu to do whatever you want, just like using a local database.

Similar thing can be done in the Visual Studio SQL Server Object Explorer. Just right click the root "Add SQL server".


问:
HashSet<T> on Windows Phone 7
Is there no System.Collections.Generic.HashSet on Windows Phone 7?</p>

答:
It is not supported on Windows Phone.  Windows Phone version of Silverlight contains some parts of regular Silverlight but not all.

See here

ContentLicense: CC BY-SA 2.5

Title: HashSet<T> on Windows Phone 7


问:
Swift 3 NSAttributedString multiple attributes
just started swift 3 and I have problems with swift syntax.

i'm trying to display a simple NSAttributedString.

so 1st I set my attributes :

```<code>let attributeFontSaySomething : [String : AnyObject] = [NSFontAttributeName : UIFont.fontSaySomething()]
let attributeColorSaySomething : [String : AnyObject] = [NSForegroundColorAttributeName : UIColor.blue]
</code>```

Then I create my string :

```<code>let attStringSaySomething = NSAttributedString(string: "Say something", attributes: self.attributeFontSaySomething)
</code>```

What i would like to do is to create the string with my 2 attributes not only just one. But when i do :

```<code>let attStringSaySomething = NSAttributedString(string: "Say something", attributes: [self.attributeFontSaySomething, self.attributeColorSaySomething])
</code>```

Xcode tells me I can't and want me to change this for a literal dictionary.

How can I create my string with the 2 attributes without using a NSMutableAttributedString ?

答:
Thanks for @vadian's answer

Update For Swift 4

```<code>let attributes : [NSAttributedStringKey : Any] = [NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue) : UIFont.systemFont(ofSize: 12.0), NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue) : UIColor(hex:"4C0000")]

refreshControl.attributedTitle=NSAttributedString(string: "Refreshing...", attributes: attributes)
</code>```

Body:
just started swift 3 and I have problems with swift syntax.

i'm trying to display a simple NSAttributedString.

so 1st I set my attributes :

let attributeFontSaySomething : [String : AnyObject] = [NSFontAttributeName : UIFont.fontSaySomething()]
let attributeColorSaySomething : [String : AnyObject] = [NSForegroundColorAttributeName : UIColor.blue]

Then I create my string :

let attStringSaySomething = NSAttributedString(string: "Say something", attributes: self.attributeFontSaySomething)

What i would like to do is to create the string with my 2 attributes not only just one. But when i do :

let attStringSaySomething = NSAttributedString(string: "Say something", attributes: [self.attributeFontSaySomething, self.attributeColorSaySomething])

Xcode tells me I can't and want me to change this for a literal dictionary.

How can I create my string with the 2 attributes without using a NSMutableAttributedString ?

Body:
Thanks for @vadian's answer

Update For Swift 4

let attributes : [NSAttributedStringKey : Any] = [NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue) : UIFont.systemFont(ofSize: 12.0), NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue) : UIColor(hex:"4C0000")]

refreshControl.attributedTitle=NSAttributedString(string: "Refreshing...", attributes: attributes)


问:
Add console output to Cucumber HTML report
I would like to add console output of tests to the Cucumber HTML report as shown here

How do i set this or do i need to write some code in the Test Runner?

答:
Kindly refer to the instructions here: https://github.com/intuit/karate/tree/master/karate-demo#example-report

This will give you the report that you see in your question.

If you use the print keyword, that will also appear.

And also refer to the answers to this question: Logging Messages from Java Class back to the Karate Report


问:
How to tell new-object is from which version of assembly?
In PowerShell, I use the following code to load two assemblies

```<code>#sql server 2012 assembly
add-type -assembly "microsoft.sqlserver.smo, version=11.0.0.0, culture=neutral, publickeytoken=89845dcd8080cc91";
#sql server 2017 assembly
add-type -assembly "microsoft.sqlserver.smo, version=14.0.0.0, culture=neutral, publickeytoken=89845dcd8080cc91";
</code>```

and I can see both assemblies are loaded successfully

```<code>[AppDomain]::CurrentDomain.GetAssemblies() | where location -like "C:\WINDOWS\assembly\GAC_MSIL\microsoft.sqlserver.smo*"
</code>```

Now if I have the following code

```<code>$svr = new-object "microsoft.sqlserver.management.smo.server" 'localhost';
</code>```

Does this $svr come from SQL Server 2012 assembly (version 11.0.0.0) or from SQL Server 2017 assembly (version 14.0.0.0)?

答:
The type will be loaded from the first assembly which you load. To see the assembly of type you can use following code:

```<code>$svr.GetType().Assembly.FullName
</code>```

If you want to see the difference, you can test a different order in a new PowerShell session.

Body:
In PowerShell, I use the following code to load two assemblies

#sql server 2012 assembly
add-type -assembly "microsoft.sqlserver.smo, version=11.0.0.0, culture=neutral, publickeytoken=89845dcd8080cc91";
#sql server 2017 assembly
add-type -assembly "microsoft.sqlserver.smo, version=14.0.0.0, culture=neutral, publickeytoken=89845dcd8080cc91";

and I can see both assemblies are loaded successfully

[AppDomain]::CurrentDomain.GetAssemblies() | where location -like "C:\WINDOWS\assembly\GAC_MSIL\microsoft.sqlserver.smo*"

Now if I have the following code

$svr = new-object "microsoft.sqlserver.management.smo.server" 'localhost';

Does this $svr come from SQL Server 2012 assembly (version 11.0.0.0) or from SQL Server 2017 assembly (version 14.0.0.0)?

Body:
The type will be loaded from the first assembly which you load. To see the assembly of type you can use following code:

$svr.GetType().Assembly.FullName

If you want to see the difference, you can test a different order in a new PowerShell session.


问:
How to show single item selected in recyclerview using kotlin
How can we mark single item is selected in Recyclerview using kotlin. When I select an item and after that click on other item then previously selected item should be dis-selected.Here is my adapter class in kotlin:..

```<code> class ListAdapter(var context: Context, var list: ArrayList<ListModel>) : RecyclerView.Adapter<ListAdapter.MyViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MyViewHolder {
        val v = LayoutInflater.from(parent?.context).inflate(R.layout.list_item, parent, false)
        return MyViewHolder(v)
    }

    override fun getItemCount(): Int {
        return list.size

    }

    override fun onBindViewHolder(holder: MyViewHolder?, position: Int) {
        holder?.bindItems(list[position])
    }

    class MyViewHolder(view: View) : RecyclerView.ViewHolder(view){

        fun bindItems(items: ListModel) {
            itemView.txt_que.text = items.que
            itemView.txt_ans.text = items.ans
            itemView.txt_sr_no.text = items.srNo
        }
}`
</code>```

答:
```<code>        if (mPosition == position)
        {
            //set selected here
        } else
        {
            //set unselected here
        }

        holder.parentView.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                mPosition = position;
                notifyDataSetChanged();
            }
        });
</code>```

Write above code in onBindViewholder and declare mPosition as global int variable in adapter class

Body:
How can we mark single item is selected in Recyclerview using kotlin. When I select an item and after that click on other item then previously selected item should be dis-selected.Here is my adapter class in kotlin:..

 class ListAdapter(var context: Context, var list: ArrayList<ListModel>) : RecyclerView.Adapter<ListAdapter.MyViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MyViewHolder {
        val v = LayoutInflater.from(parent?.context).inflate(R.layout.list_item, parent, false)
        return MyViewHolder(v)
    }

    override fun getItemCount(): Int {
        return list.size

    }

    override fun onBindViewHolder(holder: MyViewHolder?, position: Int) {
        holder?.bindItems(list[position])
    }

    class MyViewHolder(view: View) : RecyclerView.ViewHolder(view){

        fun bindItems(items: ListModel) {
            itemView.txt_que.text = items.que
            itemView.txt_ans.text = items.ans
            itemView.txt_sr_no.text = items.srNo
        }
}`

Body:
        if (mPosition == position)
        {
            //set selected here
        } else
        {
            //set unselected here
        }

        holder.parentView.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                mPosition = position;
                notifyDataSetChanged();
            }
        });

Write above code in onBindViewholder and declare mPosition as global int variable in adapter class


问:
HTML5 formatting on MacOS X? (preferably with TextMate)
Are there any editors or bundles available for MacOS X that support formatting of HTML5 documents? Tidy errors out on newer tags like canvas.</p>

答: This question talks about how to make Tidy work with HTML5; tweaking the TextMate bundle's command line to use these params should work.</p>


答:
Try with this:- take one variable in your ListModel class as

```<code>var selected:boolean  = false
</code>```

then while setting the listModel items set this value as false as

```<code>for(int i=0;i<listModel.size;i++){
   listModel.get(i).selected = false
}//this is for setting all values false
</code>```

when you select any item from list call this method and then set selected = true for selected position and simply refresh the adapter list.

in your adapter check for this selected value and accordingly set the check box value inside your bindItems method

```<code>  itemView.checkBox.selected = items.selected//this will set your checkbox selected value
</code>```

Title: How to show single item selected in recyclerview using kotlin

Body:
Try with this:- take one variable in your ListModel class as

var selected:boolean  = false

then while setting the listModel items set this value as false as

for(int i=0;i<listModel.size;i++){
   listModel.get(i).selected = false
}//this is for setting all values false

when you select any item from list call this method and then set selected = true for selected position and simply refresh the adapter list.

in your adapter check for this selected value and accordingly set the check box value inside your bindItems method

  itemView.checkBox.selected = items.selected//this will set your checkbox selected value


问:
How to set a dynamic property name in var()
I am trying to use custom properties based on dynamic values, such as attr().

For instance, in below code, I tried to access both custom-properties based on the current element's id attribute.

:root{
  --app-foo: 'Hello';
  --app-bar: 'World';
  }
div::after{
/* expected :
            'Hello' for #foo
            'World' for #bar    */
  content:  var('--app-'attr(id));
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="foo"></div>
<div id="bar"></div></code>```

But it obviously fails.

Is there some way to achieve this?

答: The grammar does not permit the first argument of a var() expression to be anything but a single custom property name that is hardcoded. This means that you cannot choose which custom property to reference in a var() expression using CSS, since it doesn't accept a string (or an attr() expression returning a string) for a property name. You'll need to set the value containing the var() expression using JS.

Body:
I am trying to use custom properties based on dynamic values, such as attr().

For instance, in below code, I tried to access both custom-properties based on the current element's id attribute.

:root{
  --app-foo: 'Hello';
  --app-bar: 'World';
  }
div::after{
/* expected :
            'Hello' for #foo
            'World' for #bar    */
  content:  var('--app-'attr(id));
  }

But it obviously fails.

Is there some way to achieve this?


问:
Tensorboard on Windows: 404 _traceDataUrl error
On Windows when I execute:

c:\python35\scripts\tensorboard --logdir=C:\Users\Kevin\Documents\dev\Deadpool\Tensorflow-SegNet\logs

and I web browse to http://localhost:6006 the first time I am redirected to http://localhost:6006/[[_traceDataUrl]] and I get the command prompt messages:

```<code>W0913 14:32:25.401402 Reloader tf_logging.py:86] Found more than one graph event per run, or there was a metagraph containing a graph_def, as well as one or more graph events.  Overwriting the graph with the newest event.
W0913 14:32:25.417002 Reloader tf_logging.py:86] Found more than one metagraph event per run. Overwriting the metagraph with the newest event.
W0913 14:32:36.446222 Thread-2 application.py:241] path /[[_traceDataUrl]] not found, sending 404
</code>```

When I try  http://localhost:6006 again, TensorBoard takes a long time presents the 404 message again but this time displays a blank web page.

Logs directory:

```<code>checkpoint
events.out.tfevents.1504911606.LTIIP82
events.out.tfevents.1504912739.LTIIP82
model.ckpt-194000.data-00000-of-00001
model.ckpt-194000.index
model.ckpt-194000.meta
</code>```

Why am I getting redirected and 404ed?

答:
I encountered the same error before, and found that it was due to internet setting problem.

On Internet Explorer, Go to Tools -> Internet Options -> Connections, click LAN settings, and then click Automatic detect settings.

Body:
On Windows when I execute:

c:\python35\scripts\tensorboard --logdir=C:\Users\Kevin\Documents\dev\Deadpool\Tensorflow-SegNet\logs

and I web browse to http://localhost:6006 the first time I am redirected to http://localhost:6006/[[_traceDataUrl]] and I get the command prompt messages:

W0913 14:32:25.401402 Reloader tf_logging.py:86] Found more than one graph event per run, or there was a metagraph containing a graph_def, as well as one or more graph events.  Overwriting the graph with the newest event.
W0913 14:32:25.417002 Reloader tf_logging.py:86] Found more than one metagraph event per run. Overwriting the metagraph with the newest event.
W0913 14:32:36.446222 Thread-2 application.py:241] path /[[_traceDataUrl]] not found, sending 404

When I try  http://localhost:6006 again, TensorBoard takes a long time presents the 404 message again but this time displays a blank web page.

Logs directory:

checkpoint
events.out.tfevents.1504911606.LTIIP82
events.out.tfevents.1504912739.LTIIP82
model.ckpt-194000.data-00000-of-00001
model.ckpt-194000.index
model.ckpt-194000.meta

Why am I getting redirected and 404ed?


问:
What's wrong with this HTML code?
I want the body part to be underneath the menu, but instead the menu is merged with the body.

http://jsfiddle.net/aqFGD/

```<code><!DOCTYPE html>
<html>
<head>
    <title>Hi</title>
    <style type="text/css">
    body
    {
        background-color: #369;
    }
    li.changeMe
    {
        background-color: #DEE;
        color: #369;
        font-weight: bold;
        padding: 8px 16px;
        margin: 5px;
        display: inline;
    }
    #bodystuff
    {
        background-color: White;
        display: block;
        padding: 15px 10px;
    }

    </style>
</head>

<body>
    <div style="margin: 15px 10px 0;">
    <div style="font-size: 30pt; font-weight: bold; color: White; font-family: Arial;">My Website</div>
    <div style="float: right; display: block; margin: 0 0 25px 0"><ul style="list-style-type: none; "><li class="changeMe">Hi</li><li class="changeMe">Hello</li></ul></div>
    <div id="bodystuff">Hi this is the body</div>
    </div>
</body>
</html>
</code>```

答:
You need to clear between your menu and body. For example:

```<code> <!--- menu stuff --->
 <div style="clear: both;"></div>
 <!--- body stuff --->
</code>```

Your example so modified: http://jsfiddle.net/redler/aqFGD/3/

Title: What's wrong with this HTML code?

Body:
I want the body part to be underneath the menu, but instead the menu is merged with the body.

http://jsfiddle.net/aqFGD/

<!DOCTYPE html>

    <title>Hi</title>

My Website

Hi

Hello

Hi this is the body

Body:
You need to clear between your menu and body. For example:

 <!--- menu stuff --->
 <div style="clear: both;"></div>
 <!--- body stuff --->

Your example so modified: http://jsfiddle.net/redler/aqFGD/3/


问:
Huawei P10 OEM toggle greyed out as disabled and fastboot (Command not allowed)
I'm having a problems to which i've been pulling my hair out and not sure what to do. Essentially, I had my phone rooted, although later decided I wanted to unroot. To unroot I used an app called "simply unroot" however it did not fully unroot my device, just made it worse, my phone does not pass the safety net, however "root checker apps" suggest my phone is not rooted, although some apps recognise my phone as being rooted. My phone bootloader is unlocked, but the OEM toggle in the developer options is not set as enabled, and is NOW greyed out so i cant click it, meaning i do not have access to any fastboot commands and thus cannot flash a recovery.img. Although, believe after having trying to unroot it had automatically disable OEM.

I have tried to lock the bootloader in the hopes that OEM toggle would no longer be greyed out, but cannot do this as i dont have access to fastboot commands. Even with TWRP i cannot flash anything just promps me with Error 9. I have tried storing the UPDATE.app within the dload folder, but that doesnt work either. I have no idea how i can recover this device. Fell like i've tried everything. Please help.

答:
In cases like yours when fastboot stops working, only way left is to use OEM provided tool to go back to factory state. Here's an XDA tutorial for P10.

Other option is to flash Magisk via the no root and no recovery method.


问:
Adding a counter to a loop
On a broad question that I haven't been able to find for R:

I'm trying to add a counter at the beginning of a loop.
So that when I run the loop sim = 1000:

```<code>if(hours$week1 > 1 and hours$week1 < 48) add 1 to the counter
ifelse add 0
</code>```

I have came across counter tutorials that print a sentence to let you know where you are (if something goes wrong):
e.g

```<code>For (i in 1:1000) {
    if (i%%100==0) print(paste("No work", i))
}
</code>```

But the purpose of my counter is to generate a value output, measuring how many of the 1000 runs in the loop fall inside a specified range.

答:
You basically had it. You just need to a) initialize the counter before the loop, b) use & instead of and in your if condition, c) actually add 1 to the counter. Since adding 0 is the same as doing nothing, you don't have to worry about the "else".

```<code>counter = 0
for (blah in your_loop_definition) {
    ... loop code ...
    if(hours$week1 > 1 & hours$week1 < 48) {
        counter = counter + 1
    }
    ... more loop code ...
}
</code>```

Title: Adding a counter to a loop

Body:
On a broad question that I haven't been able to find for R:

I'm trying to add a counter at the beginning of a loop.
So that when I run the loop sim = 1000:

if(hours$week1 > 1 and hours$week1 < 48) add 1 to the counter
ifelse add 0

I have came across counter tutorials that print a sentence to let you know where you are (if something goes wrong):
e.g

For (i in 1:1000) {
    if (i%%100==0) print(paste("No work", i))
}

But the purpose of my counter is to generate a value output, measuring how many of the 1000 runs in the loop fall inside a specified range.

Body:
You basically had it. You just need to a) initialize the counter before the loop, b) use & instead of and in your if condition, c) actually add 1 to the counter. Since adding 0 is the same as doing nothing, you don't have to worry about the "else".

counter = 0
for (blah in your_loop_definition) {
    ... loop code ...
    if(hours$week1 > 1 & hours$week1 < 48) {
        counter = counter + 1
    }
    ... more loop code ...
}


问:
What is the best way to keep my objects repository in selenium automation testing framework
My xpath value is dynamic - example -
//label[text()=$USERNAME$] - I will replace $USERNAME$ with a value "admin1" in my tests. I may click the admin and it takes me to edit page.

Need a solution considering Memory Time of execution, reliability and performance of test.

Options
1.keep it as private static final string in each page class and have a getter method for each objects ?

Keep it in properties file as key value pair load the file and get value as and when required. (Create a static class with static gettermethods for each objects which inturn call a method to load the properties instance ( properties instance is not static - values will not remain in memory - I think ) and get the key value return the value as string. Close the loaded file ?

@findby cannot be used I think bacause my test will have different values for the same xpath ?

Any other options ?

答:
You can keep all your Object Locators in Excel or JSON File.
I am keeping all my xpaths in Excel with the following Coloumns:

ElementName - Unique Name given to each element

Locator - It can contains xpath,css,className etc.

Type- Its like an indication for the locator for identifying its type (eg: ID,XPATH,CSS,CLASS,TEXT,NAME)

PageName- This is Just for Information purpose to define which page elements
belongs to.

For your Case  //label[text()=$USERNAME$], you don't need to define this full xpath in Excel. You have to just use TEXT type. Take reference from following example:

Click This Image to See Example

And while reading locators from excel you can generate xpath
.//*[text()='LOCATOR_VALUE_READ_FROM_REPOSITORY']


问:
Execute a method after the completion of a block method
I am using RNFrostedSidebar for leftmenu. While dismissing the sidebar, below block of code is executing

```<code>- (void)handleTap:(UIPanGestureRecognizer *)recognizer {
    [self dismissAnimated:YES completion:nil];
}

- (void)dismissAnimated:(BOOL)animated completion:(void (^)(BOOL finished))completion {

    void (^completionBlock)(BOOL) = ^(BOOL finished){
        [self rn_removeFromParentViewControllerCallingAppearanceMethods:YES];

        rn_frostedMenu = nil;

        if (completion) {
            completion(finished);
        }
    };

    if (animated) {
        CGFloat parentWidth = self.view.bounds.size.width;
        CGRect contentFrame = self.contentView.frame;
        contentFrame.origin.x = self.showFromRight ? parentWidth : -_width;

        CGRect blurFrame = self.blurView.frame;
        blurFrame.origin.x = self.showFromRight ? parentWidth : 0;
        blurFrame.size.width = 0;
        self.blurView.frame = blurFrame;
        self.blurView.alpha=0.1;

        [UIView animateWithDuration:self.animationDuration delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
                             self.viewForTable.frame = contentFrame;
                     }
                     completion:completionBlock];
    } else {
        completionBlock(YES);
    }
  }
</code>```

After dismissAnimated method executed i want to run a code to update the HomeViewController, That code is

```<code>[self callNavBar];

-(void) callNavBar {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"adjustNavBar"
                                                    object:self];
}
</code>```

i tried this solution, like adding the methods in queue and executing but i got exception as

"Main Thread Checker: UI API called on a background thread: -[UIView bounds]"

Then i tried this too got the same error as above.

答:
Your problem is because you didn't update ui inside UI thread. To resolve it, call dismissAnimated:completion: method inside main queue.

```<code>- (void)handleTap:(UIPanGestureRecognizer *)recognizer {
  dispatch_async(dispatch_get_main_queue(), ^{
    [self dismissAnimated:YES completion:^(BOOL finished) {
      [self callNavBar];
    }];
  });
}
</code>```

Body:
I am using RNFrostedSidebar for leftmenu. While dismissing the sidebar, below block of code is executing

- (void)handleTap:(UIPanGestureRecognizer *)recognizer {
    [self dismissAnimated:YES completion:nil];
}

- (void)dismissAnimated:(BOOL)animated completion:(void (^)(BOOL finished))completion {

    void (^completionBlock)(BOOL) = ^(BOOL finished){
        [self rn_removeFromParentViewControllerCallingAppearanceMethods:YES];

        rn_frostedMenu = nil;

        if (completion) {
            completion(finished);
        }
    };

    if (animated) {
        CGFloat parentWidth = self.view.bounds.size.width;
        CGRect contentFrame = self.contentView.frame;
        contentFrame.origin.x = self.showFromRight ? parentWidth : -_width;

        CGRect blurFrame = self.blurView.frame;
        blurFrame.origin.x = self.showFromRight ? parentWidth : 0;
        blurFrame.size.width = 0;
        self.blurView.frame = blurFrame;
        self.blurView.alpha=0.1;

        [UIView animateWithDuration:self.animationDuration delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
                             self.viewForTable.frame = contentFrame;
                     }
                     completion:completionBlock];
    } else {
        completionBlock(YES);
    }
  }

After dismissAnimated method executed i want to run a code to update the HomeViewController, That code is

[self callNavBar];

-(void) callNavBar {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"adjustNavBar"
                                                    object:self];
}

i tried this solution, like adding the methods in queue and executing but i got exception as

"Main Thread Checker: UI API called on a background thread: -[UIView bounds]"

Then i tried this too got the same error as above.

Body:
Your problem is because you didn't update ui inside UI thread. To resolve it, call dismissAnimated:completion: method inside main queue.

- (void)handleTap:(UIPanGestureRecognizer *)recognizer {
  dispatch_async(dispatch_get_main_queue(), ^{
    [self dismissAnimated:YES completion:^(BOOL finished) {
      [self callNavBar];
    }];
  });
}


问:
Shiny conditionalpanel to bypass multiple dependent sliders
I have a relatively complex app that I am building and I want users to drag coupled sliders to set the weights for some calculations. These should always sum to 100%. I looked at this and that but I have real problems with reactivity and isolation and the updateslider option seems to work for up two sliders.

So instead, I transposed the problem. I will message the user that the weights need to sum to 100% if they don't and show the example plotoutput if they do. Simples right? Well, no, as the conditions are not conforming. After looking at this and this and this, I cannot get it to work.

I provide a reproducible example below to demonstrate this problem - I suspect it's because of my awkwardness with reactivity and observers in shiny.

```<code>library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

   # Application title
   titlePanel("testing 1 2 3"),

   # Sidebar with a slider input for number of bins
   sidebarLayout(
      sidebarPanel(
      ),

      # Show a plot of the generated distribution
      mainPanel(
         fluidRow(

            column(width = 2,
                   offset = 0,
                   align = "center",
                   sliderInput(inputId = "sld_1",
                               label = "weight",
                               min = 0,
                               max = 1,
                               value = 0.25,
                               step = 0.05,
                               animate = TRUE)
                   ,
                   sliderInput(inputId = "sld_2",
                               label = "weight",
                               min = 0,
                               max = 1,
                               value = 0.25,
                               step = 0.05,
                               animate = TRUE)
                   ,
                   sliderInput(inputId = "sld_3",
                               label = "weight",
                               min = 0,
                               max = 1,
                               value = 0.25,
                               step = 0.05,
                               animate = TRUE)
                   ,
                   sliderInput(inputId = "sld_4",
                               label = "weight",
                               min = 0,
                               max = 1,
                               value = 0.25,
                               step = 0.05,
                               animate = TRUE)
            ) #slider columns
            ,
            column(width = 9,
                   offset = 0,
                   align = "center",
                   conditionalPanel(
                      condition = "output.myCondition == FALSE",
                      textOutput(outputId = "distPrint")
                   ) #conditional1
                   ,
                   conditionalPanel(
                      condition = "output.myCondition == TRUE",
                      plotOutput(outputId = "distPlot")
                   ) #conditional2
            ) #column
         )#fluidrow
      )
   )
)

# Define server logic required to draw a histogram
server <- function(input, output,session) {

   dister <-   reactive({
      if( !is.null(input$sld_1) &&
          !is.null(input$sld_2) &&
          !is.null(input$sld_3) &&
          !is.null(input$sld_4) &&
          sum(input$sld_1,input$sld_2,input$sld_3,input$sld_4)==1
      ) {
         rnorm(input$sld_1*1000)
      } else {c(0,1,2,3,4,5)}
   })

   output.myCondition <- reactive({
      if( !is.null(input$sld_1) &&
          !is.null(input$sld_2) &&
          !is.null(input$sld_3) &&
          !is.null(input$sld_4) &&
          sum(input$sld_1,input$sld_2,input$sld_3,input$sld_4)==1
      ) {
              TRUE
      } else {FALSE}
   })

   output$distPlot <- renderPlot({
      x<-dister()
      hist(x)
   })

   output$distPrint <- renderText({
      print("The weights must sum to 100%")
   })
}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

答:
You were nearly ther. What you need to do is use your reactive expression output.myCondition in renderText as follows:

```<code> output$distPrint <- renderText({
    if(output.myCondition()){
      print("")
    }else
    {
      print("The weights must sum to 100%")
    }

  })
</code>```

[EDIT]:

I seem to have misunderstood your query. I know that this question has already been answered I thought I will provide an alternate solution for anyone whom it might stumble upon here. Here I have added if else in both renderText and renderPlot based on the output of output.myCondition().Here is the updated server code.

```<code>server <- function(input, output,session) {

      dister <-   reactive({
        if( !is.null(input$sld_1) &&
            !is.null(input$sld_2) &&
            !is.null(input$sld_3) &&
            !is.null(input$sld_4) &&
            sum(input$sld_1,input$sld_2,input$sld_3,input$sld_4)==1
        ) {
          rnorm(input$sld_1*1000)
        } else {c(0,1,2,3,4,5)}
      })

      output.myCondition <- reactive({
        if( !is.null(input$sld_1) &&
            !is.null(input$sld_2) &&
            !is.null(input$sld_3) &&
            !is.null(input$sld_4) &&
            sum(input$sld_1,input$sld_2,input$sld_3,input$sld_4)==1
        ) {
          TRUE
        } else {FALSE}
      })

      output$distPlot <- renderPlot({
        if(output.myCondition()){
        x<-dister()
        hist(x)
        }else
        {
         NULL
        }
      })

      output$distPrint <- renderText({
        if(output.myCondition()){
          print("")
        }else
        {
          print("The weights must sum to 100%")
        }

      })
    }
</code>```

Body:
I have a relatively complex app that I am building and I want users to drag coupled sliders to set the weights for some calculations. These should always sum to 100%. I looked at this and that but I have real problems with reactivity and isolation and the updateslider option seems to work for up two sliders.

So instead, I transposed the problem. I will message the user that the weights need to sum to 100% if they don't and show the example plotoutput if they do. Simples right? Well, no, as the conditions are not conforming. After looking at this and this and this, I cannot get it to work.

I provide a reproducible example below to demonstrate this problem - I suspect it's because of my awkwardness with reactivity and observers in shiny.

library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

   # Application title
   titlePanel("testing 1 2 3"),

   # Sidebar with a slider input for number of bins
   sidebarLayout(
      sidebarPanel(
      ),

      # Show a plot of the generated distribution
      mainPanel(
         fluidRow(

            column(width = 2,
                   offset = 0,
                   align = "center",
                   sliderInput(inputId = "sld_1",
                               label = "weight",
                               min = 0,
                               max = 1,
                               value = 0.25,
                               step = 0.05,
                               animate = TRUE)
                   ,
                   sliderInput(inputId = "sld_2",
                               label = "weight",
                               min = 0,
                               max = 1,
                               value = 0.25,
                               step = 0.05,
                               animate = TRUE)
                   ,
                   sliderInput(inputId = "sld_3",
                               label = "weight",
                               min = 0,
                               max = 1,
                               value = 0.25,
                               step = 0.05,
                               animate = TRUE)
                   ,
                   sliderInput(inputId = "sld_4",
                               label = "weight",
                               min = 0,
                               max = 1,
                               value = 0.25,
                               step = 0.05,
                               animate = TRUE)
            ) #slider columns
            ,
            column(width = 9,
                   offset = 0,
                   align = "center",
                   conditionalPanel(
                      condition = "output.myCondition == FALSE",
                      textOutput(outputId = "distPrint")
                   ) #conditional1
                   ,
                   conditionalPanel(
                      condition = "output.myCondition == TRUE",
                      plotOutput(outputId = "distPlot")
                   ) #conditional2
            ) #column
         )#fluidrow
      )
   )
)

# Define server logic required to draw a histogram
server <- function(input, output,session) {

   dister <-   reactive({
      if( !is.null(input$sld_1) &&
          !is.null(input$sld_2) &&
          !is.null(input$sld_3) &&
          !is.null(input$sld_4) &&
          sum(input$sld_1,input$sld_2,input$sld_3,input$sld_4)==1
      ) {
         rnorm(input$sld_1*1000)
      } else {c(0,1,2,3,4,5)}
   })

   output.myCondition <- reactive({
      if( !is.null(input$sld_1) &&
          !is.null(input$sld_2) &&
          !is.null(input$sld_3) &&
          !is.null(input$sld_4) &&
          sum(input$sld_1,input$sld_2,input$sld_3,input$sld_4)==1
      ) {
              TRUE
      } else {FALSE}
   })

   output$distPlot <- renderPlot({
      x<-dister()
      hist(x)
   })

   output$distPrint <- renderText({
      print("The weights must sum to 100%")
   })
}

# Run the application
shinyApp(ui = ui, server = server)

Body:
You were nearly ther. What you need to do is use your reactive expression output.myCondition in renderText as follows:

 output$distPrint <- renderText({
    if(output.myCondition()){
      print("")
    }else
    {
      print("The weights must sum to 100%")
    }

  })

[EDIT]:

I seem to have misunderstood your query. I know that this question has already been answered I thought I will provide an alternate solution for anyone whom it might stumble upon here. Here I have added if else in both renderText and renderPlot based on the output of output.myCondition().Here is the updated server code.

server <- function(input, output,session) {

      dister <-   reactive({
        if( !is.null(input$sld_1) &&
            !is.null(input$sld_2) &&
            !is.null(input$sld_3) &&
            !is.null(input$sld_4) &&
            sum(input$sld_1,input$sld_2,input$sld_3,input$sld_4)==1
        ) {
          rnorm(input$sld_1*1000)
        } else {c(0,1,2,3,4,5)}
      })

      output.myCondition <- reactive({
        if( !is.null(input$sld_1) &&
            !is.null(input$sld_2) &&
            !is.null(input$sld_3) &&
            !is.null(input$sld_4) &&
            sum(input$sld_1,input$sld_2,input$sld_3,input$sld_4)==1
        ) {
          TRUE
        } else {FALSE}
      })

      output$distPlot <- renderPlot({
        if(output.myCondition()){
        x<-dister()
        hist(x)
        }else
        {
         NULL
        }
      })

      output$distPrint <- renderText({
        if(output.myCondition()){
          print("")
        }else
        {
          print("The weights must sum to 100%")
        }

      })
    }


问:
What do I write in .htaccess to hide ?variablename= in the URL?
My current .htaccess file says:

```<code>Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /

# new rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/.]+)/?$ ?variablename=$1
</code>```

This allows me to type www.mysite.com/somevalue and it works.  But if I click the button to submit a value like VALUE, it turns the above URL to www.mysite.com/somevalue?variablename=VALUE

And if I'm at www.mysite.com it will go to wwww.mysite.com/?variablename=VALUE

I want it to work so when the user submits a value it goes to www.mysite.com/theusersvalue

答:
Maybe this is what you want:
Use .htaccess to hide variables

Add this piece of code on the htaccess file:

```<code>RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /\?page=([^&\ ]+)
RewriteRule ^/?$ /%1? [L,R=301]
</code>```

Body:
My current .htaccess file says:

Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /

# new rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/.]+)/?$ ?variablename=$1

This allows me to type www.mysite.com/somevalue and it works.  But if I click the button to submit a value like VALUE, it turns the above URL to www.mysite.com/somevalue?variablename=VALUE

And if I'm at www.mysite.com it will go to wwww.mysite.com/?variablename=VALUE

I want it to work so when the user submits a value it goes to www.mysite.com/theusersvalue

Body:
Maybe this is what you want:
Use .htaccess to hide variables

Add this piece of code on the htaccess file:

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /\?page=([^&\ ]+)
RewriteRule ^/?$ /%1? [L,R=301]


问:
Rails get record newest in many has_many
I have some model like this:

```<code>class LogActivity < ActiveRecord::Base
   has_many :call_logs
   has_many :send_email_logs
   has_many :send_sms_logs
   ...
end

class CallLog < ActiveRecord::Base
   belongs_to :log_activity
end

class SendEmailLog < ActiveRecord::Base
   belongs_to :log_activity
end

class SendSmsLog < ActiveRecord::Base
   belongs_to :log_activity
end
</code>```

Now, i want get one newest record in :call_logs, :send_email_logs, :send_sms_logs. How can i do that???

答:
You can try like below:

```<code>LogActivity.joins(:call_logs, :send_email_logs, :send_sms_logs).where(log_activity_id: 1 or something)
</code>```

For more explanation, you can look the rails guide link

Thanks

Body:
I have some model like this:

class LogActivity < ActiveRecord::Base
   has_many :call_logs
   has_many :send_email_logs
   has_many :send_sms_logs
   ...
end

class CallLog < ActiveRecord::Base
   belongs_to :log_activity
end

class SendEmailLog < ActiveRecord::Base
   belongs_to :log_activity
end

class SendSmsLog < ActiveRecord::Base
   belongs_to :log_activity
end

Now, i want get one newest record in :call_logs, :send_email_logs, :send_sms_logs. How can i do that???

Body:
You can try like below:

LogActivity.joins(:call_logs, :send_email_logs, :send_sms_logs).where(log_activity_id: 1 or something)

For more explanation, you can look the rails guide link

Thanks


问:
ng-repeat values in single input with comma separated
I have list array.Inside that I have one nested array called types.
I am trying to show types.work inside an input field with comma separated.

This is what I have tried:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
 $scope.init = function(){
 $scope.list=[
   {
     "name":"john",
     "types":[
       {"work":"aa"},
       {"work":"bb"}
     ]
   }
 ];
      }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="MainCtrl" ng-init="init()">
   <input type="text" ng-model="list.name">
   <label ng-repeat="data in list.types">{{data.work}}{{$last ? '' : ', '}}</label>
  </div>
</div></code>```

Can anyone tell me that how to use ng-repeat values in single input?.

答:
You added the list an array so you can use ng-repeat in ng-repeat or you can directly use array first object like this</p>

```<code><input type="text" ng-model="list[0].name">
<label ng-repeat="data in list[0].types">{{data.work}}{{$last ? '' : ', '}}</label>
</code>```

Body:
I have list array.Inside that I have one nested array called types.
I am trying to show types.work inside an input field with comma separated.

This is what I have tried:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
 $scope.init = function(){
 $scope.list=[
   {
     "name":"john",
     "types":[
       {"work":"aa"},
       {"work":"bb"}
     ]
   }
 ];
      }
});

   <input type="text" ng-model="list.name">
   {{data.work}}{{$last ? '' : ', '}}

Can anyone tell me that how to use ng-repeat values in single input?.

Body:
You added the list an array so you can use ng-repeat in ng-repeat or you can directly use array first object like this

<input type="text" ng-model="list[0].name">
<label ng-repeat="data in list[0].types">{{data.work}}{{$last ? '' : ', '}}</label>


问:
Electron-packager does not package node modules which names are started from "@"
I create desktop application by using electron, and tried electron-packager.
But electron-packager doesn't package node modules which names are started from "@" (Example: @turf, @mapbox)

In node_modules folder of developing folder, I can find "@turf" and "@mapbox".

But after running

```<code>>electron-packager . MaplatEditor --platform=darwin --arch=x64 --electron-version=1.7.9
</code>```

Created package never includes "@turf" and "@mapbox".
And also, it's depending modules are also not included.

My package.json includes "@turf", so it is not setting error.

```<code>{
  "name": "MaplatEditor",
  "version": "1.0.0",
  "description": "",
  "main": "lib/main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@turf/turf": "^4.6.1",
    "argv": "0.0.2",
    "async": "^2.5.0",
    "child_process": "^1.0.2",
    "electron-json-storage": "^3.2.0",
    "file-url": "^2.0.2",
    "fs-extra": "^3.0.1",
    "imagemagick": "^0.1.3",
    "mapshaper": "^0.4.31",
    "path": "^0.12.7",
    "wellknown": "^0.5.0"
  }
}
</code>```

How can I package such @-started modules into application package?

答:
In my case, I updated @Turf module for latest version, then electron-packager worked well.
I don't know why, but it looks not the issue of electron-packager...</p>

Body:
I create desktop application by using electron, and tried electron-packager.
But electron-packager doesn't package node modules which names are started from "@" (Example: @turf, @mapbox)

In node_modules folder of developing folder, I can find "@turf" and "@mapbox".

But after running

>electron-packager . MaplatEditor --platform=darwin --arch=x64 --electron-version=1.7.9

Created package never includes "@turf" and "@mapbox".
And also, it's depending modules are also not included.

My package.json includes "@turf", so it is not setting error.

{
  "name": "MaplatEditor",
  "version": "1.0.0",
  "description": "",
  "main": "lib/main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@turf/turf": "^4.6.1",
    "argv": "0.0.2",
    "async": "^2.5.0",
    "child_process": "^1.0.2",
    "electron-json-storage": "^3.2.0",
    "file-url": "^2.0.2",
    "fs-extra": "^3.0.1",
    "imagemagick": "^0.1.3",
    "mapshaper": "^0.4.31",
    "path": "^0.12.7",
    "wellknown": "^0.5.0"
  }
}

How can I package such @-started modules into application package?


问:
deactivate account from firebase chat app
i'm using the firebase database for my chat application, When i click on the deactivate button it deletes the user from the Authentication section of firebase but not from the database section of firebase and my all user activity retrieve the user data from the database section. because of this when a user deactivate his account it get delete, but his account is still visible to the other user. below this i'm attaching my codes..

```<code>public class SettingsActivity extends AppCompatActivity{

    ImageView ivCamera;

    private DatabaseReference mUserDatabase;
    private FirebaseUser mCurrentUser;

    private CircleImageView mDisplayImage;
    private TextView mName;
    private TextView mStatus;

    private Button mProfileBtn;
    private Button mDeactivateBtn;
    //private Button mImageBtn;

    private static final int GALLERY_PICK = 1;

    private StorageReference mImageStorage;

    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        mDisplayImage = (CircleImageView) findViewById(R.id.settings_image);
        mName = (TextView) findViewById(R.id.settings_name);
        mStatus = (TextView) findViewById(R.id.settings_status);

        mProfileBtn = (Button) findViewById(R.id.settings_profile_btn);
        mDeactivateBtn = (Button) findViewById(R.id.deactivate_btn);
        ivCamera = (ImageView) findViewById(R.id.ivCamera);
        mProgressDialog = new ProgressDialog(this);

        mImageStorage = FirebaseStorage.getInstance().getReference();

        mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();

        String current_uid = mCurrentUser.getUid();

        mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid);

        mUserDatabase.keepSynced(true);

        mUserDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                String name = dataSnapshot.child("name").getValue().toString();
                final String image = dataSnapshot.child("image").getValue().toString();
                String status = dataSnapshot.child("status").getValue().toString();
                String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();

                mName.setText(name);
                mStatus.setText(status);

                if (!image.equals("default")) {

                    //Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.avatar).into(mDisplayImage);
                    Picasso.with(SettingsActivity.this).load(image).networkPolicy(NetworkPolicy.OFFLINE)
                            .placeholder(R.drawable.avatar).into(mDisplayImage, new Callback() {
                        @Override
                        public void onSuccess() {

                        }

                        @Override
                        public void onError() {

                            Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.avatar).into(mDisplayImage);
                        }
                    });

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        //ivGallery =(ImageView) findViewById(R.id.ivGallery);

        //ivGallery.setOnClickListener(new View.OnClickListener() {
        //   @Override
        // public void onClick(View view) {

        //}
        //});

        mProfileBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String name_value = mName.getText().toString();
                String status_value = mStatus.getText().toString();

                Intent status_Intent = new Intent(SettingsActivity.this, StatusActivity.class);
                status_Intent.putExtra("status_value", status_value);
                status_Intent.putExtra("name_value", name_value);

                startActivity(status_Intent);
            }

        });

        ivCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent galleryIntent = new Intent();
                galleryIntent.setType("image/*");
                galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

                startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICK);

            }

        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {

            Uri imageUri = data.getData();

            CropImage.activity(imageUri).setAspectRatio(1, 1).start(this);

            //Toast.makeText(SettingsActivity.this, imageUri, Toast.LENGTH_LONG).show();

        }
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {

            CropImage.ActivityResult result = CropImage.getActivityResult(data);

            if (resultCode == RESULT_OK) {

                mProgressDialog = new ProgressDialog(SettingsActivity.this);
                mProgressDialog.setTitle("Uploading Image.....");
                mProgressDialog.setMessage("Please wait while we upload and process the image.");
                mProgressDialog.setCanceledOnTouchOutside(false);
                mProgressDialog.show();

                Uri resultUri = result.getUri();

                File thumb_filePath = new File(resultUri.getPath());

                String current_user_id = mCurrentUser.getUid();

                Bitmap thumb_bitmap = new Compressor(this)
                        .setMaxWidth(200)
                        .setMaxHeight(200)
                        .setQuality(75)
                        .compressToBitmap(thumb_filePath);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                final byte[] thumb_byte = baos.toByteArray();

                StorageReference filePath = mImageStorage.child("profile_images").child(current_user_id + ".jpg");

                final StorageReference thumb_filepath = mImageStorage.child("profile_images").child("thumbs").child(current_user_id + ".jpg");

                filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {

                        if (task.isSuccessful()) {

                            final String download_url = task.getResult().getDownloadUrl().toString();

                            UploadTask uploadTask = thumb_filepath.putBytes(thumb_byte);
                            uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                                @Override
                                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> thumb_task) {

                                    String thumb_downloadUrl = thumb_task.getResult().getDownloadUrl().toString();

                                    if (thumb_task.isSuccessful()) {

                                        Map update_hashMap = new HashMap();
                                        update_hashMap.put("image", download_url);
                                        update_hashMap.put("thumb_image", thumb_downloadUrl);

                                        mUserDatabase.updateChildren(update_hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                                            @Override
                                            public void onComplete(@NonNull Task<Void> task) {
                                                if (task.isSuccessful()) {

                                                    mProgressDialog.dismiss();
                                                    Toast.makeText(SettingsActivity.this, "Success Uploading.", Toast.LENGTH_LONG).show();
                                                }
                                            }
                                        });
                                    } else {

                                        Toast.makeText(SettingsActivity.this, "Error in Uploading thumbnail.", Toast.LENGTH_LONG).show();
                                        mProgressDialog.dismiss();
                                    }
                                }
                            });

                        } else {

                            Toast.makeText(SettingsActivity.this, "Error in Uploading.", Toast.LENGTH_LONG).show();
                            mProgressDialog.dismiss();
                        }
                    }
                });

            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {

                Exception error = result.getError();
            }
        }
    }

    public static String random() {
        Random generator = new Random();
        StringBuilder randomStringBuilder = new StringBuilder();
        int randomLength = generator.nextInt(10);
        char tempChar;
        for (int i = 0; i < randomLength; i++) {
            tempChar = (char) (generator.nextInt(96) + 32);
            randomStringBuilder.append(tempChar);
        }
        return randomStringBuilder.toString();
    }

            public void deactivate(View view)
            {
              FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
            if (user!=null)
            {
             mProgressDialog.setTitle("Deactivate Account");
            mProgressDialog.setMessage("Deactivating...");
              mProgressDialog.show();
              mUserDatabase.child(mCurrentUser.getUid()).removeValue();
             user.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
                 public void onComplete(@NonNull Task<Void> task) {
                     if (task.isSuccessful()) {
                         Toast.makeText(getApplicationContext(), "Account is Deactivated", Toast.LENGTH_LONG).show();
                         finish();
                         Intent intent = new Intent(SettingsActivity.this, RegisterActivity.class);
                         startActivity(intent);
                     } else {
                         Toast.makeText(getApplicationContext(), "Account could not be Deactivate", Toast.LENGTH_LONG).show();
                     }
                     mProgressDialog.dismiss();
                 }
             });
              }
            }
}
</code>```

i want that when the user deactivate his account it will not visible anymore in the all user activity

答:
There are multiple ways to doing this.

When you delete account of user. You should delete all nodes attaching to that user. so that any activity related to user will not be visible to other users.!

if you don't want to remove from database section. you can put another key value with the name of status. if user status is deleted or disable. don't fetch the data of that user in activity.

Hope this will help you to answer your question.
if you've still questions in your mind, you can ask.

For deleting child:

```<code> rootRef.child(node).removeValue();
</code>```

Simple deleting the node.

you can customize it according to your need.

Body:
i'm using the firebase database for my chat application, When i click on the deactivate button it deletes the user from the Authentication section of firebase but not from the database section of firebase and my all user activity retrieve the user data from the database section. because of this when a user deactivate his account it get delete, but his account is still visible to the other user. below this i'm attaching my codes..

public class SettingsActivity extends AppCompatActivity{

    ImageView ivCamera;

    private DatabaseReference mUserDatabase;
    private FirebaseUser mCurrentUser;

    private CircleImageView mDisplayImage;
    private TextView mName;
    private TextView mStatus;

    private Button mProfileBtn;
    private Button mDeactivateBtn;
    //private Button mImageBtn;

    private static final int GALLERY_PICK = 1;

    private StorageReference mImageStorage;

    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        mDisplayImage = (CircleImageView) findViewById(R.id.settings_image);
        mName = (TextView) findViewById(R.id.settings_name);
        mStatus = (TextView) findViewById(R.id.settings_status);

        mProfileBtn = (Button) findViewById(R.id.settings_profile_btn);
        mDeactivateBtn = (Button) findViewById(R.id.deactivate_btn);
        ivCamera = (ImageView) findViewById(R.id.ivCamera);
        mProgressDialog = new ProgressDialog(this);

        mImageStorage = FirebaseStorage.getInstance().getReference();

        mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();

        String current_uid = mCurrentUser.getUid();

        mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid);

        mUserDatabase.keepSynced(true);

        mUserDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                String name = dataSnapshot.child("name").getValue().toString();
                final String image = dataSnapshot.child("image").getValue().toString();
                String status = dataSnapshot.child("status").getValue().toString();
                String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();

                mName.setText(name);
                mStatus.setText(status);

                if (!image.equals("default")) {

                    //Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.avatar).into(mDisplayImage);
                    Picasso.with(SettingsActivity.this).load(image).networkPolicy(NetworkPolicy.OFFLINE)
                            .placeholder(R.drawable.avatar).into(mDisplayImage, new Callback() {
                        @Override
                        public void onSuccess() {

                        }

                        @Override
                        public void onError() {

                            Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.avatar).into(mDisplayImage);
                        }
                    });

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        //ivGallery =(ImageView) findViewById(R.id.ivGallery);

        //ivGallery.setOnClickListener(new View.OnClickListener() {
        //   @Override
        // public void onClick(View view) {

        //}
        //});

        mProfileBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String name_value = mName.getText().toString();
                String status_value = mStatus.getText().toString();

                Intent status_Intent = new Intent(SettingsActivity.this, StatusActivity.class);
                status_Intent.putExtra("status_value", status_value);
                status_Intent.putExtra("name_value", name_value);

                startActivity(status_Intent);
            }

        });

        ivCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent galleryIntent = new Intent();
                galleryIntent.setType("image/*");
                galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

                startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICK);

            }

        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {

            Uri imageUri = data.getData();

            CropImage.activity(imageUri).setAspectRatio(1, 1).start(this);

            //Toast.makeText(SettingsActivity.this, imageUri, Toast.LENGTH_LONG).show();

        }
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {

            CropImage.ActivityResult result = CropImage.getActivityResult(data);

            if (resultCode == RESULT_OK) {

                mProgressDialog = new ProgressDialog(SettingsActivity.this);
                mProgressDialog.setTitle("Uploading Image.....");
                mProgressDialog.setMessage("Please wait while we upload and process the image.");
                mProgressDialog.setCanceledOnTouchOutside(false);
                mProgressDialog.show();

                Uri resultUri = result.getUri();

                File thumb_filePath = new File(resultUri.getPath());

                String current_user_id = mCurrentUser.getUid();

                Bitmap thumb_bitmap = new Compressor(this)
                        .setMaxWidth(200)
                        .setMaxHeight(200)
                        .setQuality(75)
                        .compressToBitmap(thumb_filePath);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                final byte[] thumb_byte = baos.toByteArray();

                StorageReference filePath = mImageStorage.child("profile_images").child(current_user_id + ".jpg");

                final StorageReference thumb_filepath = mImageStorage.child("profile_images").child("thumbs").child(current_user_id + ".jpg");

                filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {

                        if (task.isSuccessful()) {

                            final String download_url = task.getResult().getDownloadUrl().toString();

                            UploadTask uploadTask = thumb_filepath.putBytes(thumb_byte);
                            uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                                @Override
                                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> thumb_task) {

                                    String thumb_downloadUrl = thumb_task.getResult().getDownloadUrl().toString();

                                    if (thumb_task.isSuccessful()) {

                                        Map update_hashMap = new HashMap();
                                        update_hashMap.put("image", download_url);
                                        update_hashMap.put("thumb_image", thumb_downloadUrl);

                                        mUserDatabase.updateChildren(update_hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                                            @Override
                                            public void onComplete(@NonNull Task<Void> task) {
                                                if (task.isSuccessful()) {

                                                    mProgressDialog.dismiss();
                                                    Toast.makeText(SettingsActivity.this, "Success Uploading.", Toast.LENGTH_LONG).show();
                                                }
                                            }
                                        });
                                    } else {

                                        Toast.makeText(SettingsActivity.this, "Error in Uploading thumbnail.", Toast.LENGTH_LONG).show();
                                        mProgressDialog.dismiss();
                                    }
                                }
                            });

                        } else {

                            Toast.makeText(SettingsActivity.this, "Error in Uploading.", Toast.LENGTH_LONG).show();
                            mProgressDialog.dismiss();
                        }
                    }
                });

            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {

                Exception error = result.getError();
            }
        }
    }

    public static String random() {
        Random generator = new Random();
        StringBuilder randomStringBuilder = new StringBuilder();
        int randomLength = generator.nextInt(10);
        char tempChar;
        for (int i = 0; i < randomLength; i++) {
            tempChar = (char) (generator.nextInt(96) + 32);
            randomStringBuilder.append(tempChar);
        }
        return randomStringBuilder.toString();
    }

            public void deactivate(View view)
            {
              FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
            if (user!=null)
            {
             mProgressDialog.setTitle("Deactivate Account");
            mProgressDialog.setMessage("Deactivating...");
              mProgressDialog.show();
              mUserDatabase.child(mCurrentUser.getUid()).removeValue();
             user.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
                 public void onComplete(@NonNull Task<Void> task) {
                     if (task.isSuccessful()) {
                         Toast.makeText(getApplicationContext(), "Account is Deactivated", Toast.LENGTH_LONG).show();
                         finish();
                         Intent intent = new Intent(SettingsActivity.this, RegisterActivity.class);
                         startActivity(intent);
                     } else {
                         Toast.makeText(getApplicationContext(), "Account could not be Deactivate", Toast.LENGTH_LONG).show();
                     }
                     mProgressDialog.dismiss();
                 }
             });
              }
            }
}

i want that when the user deactivate his account it will not visible anymore in the all user activity

Body:
There are multiple ways to doing this.

When you delete account of user. You should delete all nodes attaching to that user. so that any activity related to user will not be visible to other users.!

if you don't want to remove from database section. you can put another key value with the name of status. if user status is deleted or disable. don't fetch the data of that user in activity.

Hope this will help you to answer your question.
if you've still questions in your mind, you can ask.

For deleting child:

 rootRef.child(node).removeValue();

Simple deleting the node.

you can customize it according to your need.


问:
HashSet<T> on Windows Phone 7
Is there no System.Collections.Generic.HashSet on Windows Phone 7?</p>

答: The Windows Phone 7 .NET libraries are comparable to what is provided in Silverlight 3.0 (which doesn't have HashSet).  You can build something like a HashSet using a Dictionary.  For example, see this MSDN forum post: http://social.msdn.microsoft.com/Forums/en-US/windowsphone7series/thread/e1dd3571-dfb8-4abe-b63a-62106d6a4965/

Title: HashSet<T> on Windows Phone 7


问:
Asp net core query string params serialization
Can I use complex types as query string params for the HttpGet request in Asp.NET Core MVC app?

I had a problem with it, when i try to pass the param as complex type, like this:

```<code>[Route("reportData")]
[HttpGet]
public List<dynamic> GetReportData(int reportId, int scope [FromQuery] ReportFilterMetadataDto filters)
{
    ...
}
</code>```

all of properties in filters objects have null value. But if I pass filters like string and deserialize it into destination type, like this:

```<code>[Route("reportData")]
[HttpGet]
public List<dynamic> GetReportData(int reportId, int, string filters)
{
    var result = JsonConvert.DeserializeObject<ReportFilterMetadataDto>(filters);
}
</code>```

there are no problems. Is it necessary to implement custom serializer or configure asp net core app MVC, or use middleware to getting correct result. Maybe I done anything in the wrong way?

答:
They are probably null due to a binding failure.
Try the following:

```<code>   [HttpGet("reportData/{reportId}/{scope}")]
   public List<dynamic> GetReportData(int reportId, int scope [FromQuery]
       ReportFilterMetadataDto filters)
   {
      ...
   }
</code>```

You can also have multiple FromQuery attributes. However, with the amount of information you are getting, maybe consider this method as Post and send get the dto FromBody.

Body:
Can I use complex types as query string params for the HttpGet request in Asp.NET Core MVC app?

I had a problem with it, when i try to pass the param as complex type, like this:

[Route("reportData")]
[HttpGet]
public List<dynamic> GetReportData(int reportId, int scope [FromQuery] ReportFilterMetadataDto filters)
{
    ...
}

all of properties in filters objects have null value. But if I pass filters like string and deserialize it into destination type, like this:

[Route("reportData")]
[HttpGet]
public List<dynamic> GetReportData(int reportId, int, string filters)
{
    var result = JsonConvert.DeserializeObject<ReportFilterMetadataDto>(filters);
}

there are no problems. Is it necessary to implement custom serializer or configure asp net core app MVC, or use middleware to getting correct result. Maybe I done anything in the wrong way?

Body:
They are probably null due to a binding failure.
Try the following:

   [HttpGet("reportData/{reportId}/{scope}")]
   public List<dynamic> GetReportData(int reportId, int scope [FromQuery]
       ReportFilterMetadataDto filters)
   {
      ...
   }

You can also have multiple FromQuery attributes. However, with the amount of information you are getting, maybe consider this method as Post and send get the dto FromBody.


问:
Change UWP menu button icon image in title bar (simple way)
I want a hamburger menu button in my UWP app title bar.

I already know how to make a "back" button visible in the title bar and how to handle its clicked event.
I have seen samples of how to customize the title bars colors and stuff, and I have also seen some samples of how to put controls in it, but its all too much complicated.

答: If you are looking for a simple hamburger control, here is a video tutorial I followed to while learning. It is simple and does the work pretty well. The source is available on the provided link. Please mark as answer if it helped you.</p>


答:
You have a float above the "body" part, and you are not clearing before new content.

Floating elements have to be cleared, ie. stop floating stuff and start a new.

http://jsfiddle.net/aqFGD/1/

See the modifications in the updated demo.

```<code><br style="clear: both;" />
</code>```

Title: What's wrong with this HTML code?

Body:
I want the body part to be underneath the menu, but instead the menu is merged with the body.

http://jsfiddle.net/aqFGD/

<!DOCTYPE html>

    <title>Hi</title>

My Website

Hi

Hello

Hi this is the body

Body:
You have a float above the "body" part, and you are not clearing before new content.

Floating elements have to be cleared, ie. stop floating stuff and start a new.

http://jsfiddle.net/aqFGD/1/

See the modifications in the updated demo.

<br style="clear: both;" />