问:
UISearchController search bar overlap first cell when active
I am using UISearchController to search for data in my tableview. I am not using table view controller. I would like to hide the navigation bar when my search bar is active therefore I set self.searchController.hidesNavigationBarDuringPresentation = YES; to yes.

However when I do this and want to search, my active search bar covers part of the first cell. the covered part has same height as status bar.

I tried other articles and questions similar to this one but nothing helped me to solve it. Then I started to play with the table view header size. I did this

```<code> -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

  return 20.0f;
}
</code>```

The result was that when I tapped search bar an started to search problem was not there anymore.

However when the search bar is not active there was a gab between searchbar and first cell

Any ideas how to fix this issue?

Edit: after adding self.automaticallyAdjustsScrollViewInsets = false;

答:
This is how I set up the search bar and things in viewDidLoad (copied from some of apple's examples).

It presents the found results in the same view controller as your unfiltered data is shown. It also has its search bar in the table header that is hidden until it is needed.

```<code>self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.tableView.tableHeaderView = self.searchController.searchBar;
[self.searchController.searchBar sizeToFit];

// we want to be the delegate for our filtered table so didSelectRowAtIndexPath is called for both tables
self.searchController.delegate = self;
self.searchController.dimsBackgroundDuringPresentation = NO; // default is YES
self.searchController.searchBar.delegate = self; // so we can monitor text changes + others

// Search is now just presenting a view controller. As such, the normal view controller
// presentation semantics apply. Namely, that presentation will walk up the view controller
// hierarchy until it finds the root view controller or one that defines a presentation context.
//
self.definesPresentationContext = YES;  // know where you want UISearchController to be displayed

// Hides search bar initially. When the user pulls down on the list, the search bar is revealed.
[self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height)];
</code>```

Body:
I am using UISearchController to search for data in my tableview. I am not using table view controller. I would like to hide the navigation bar when my search bar is active therefore I set self.searchController.hidesNavigationBarDuringPresentation = YES; to yes.

However when I do this and want to search, my active search bar covers part of the first cell. the covered part has same height as status bar.

I tried other articles and questions similar to this one but nothing helped me to solve it. Then I started to play with the table view header size. I did this

 -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

  return 20.0f;
}

The result was that when I tapped search bar an started to search problem was not there anymore.

However when the search bar is not active there was a gab between searchbar and first cell

Any ideas how to fix this issue?

Edit: after adding self.automaticallyAdjustsScrollViewInsets = false;

Body:
This is how I set up the search bar and things in viewDidLoad (copied from some of apple's examples).

It presents the found results in the same view controller as your unfiltered data is shown. It also has its search bar in the table header that is hidden until it is needed.

self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.tableView.tableHeaderView = self.searchController.searchBar;
[self.searchController.searchBar sizeToFit];

// we want to be the delegate for our filtered table so didSelectRowAtIndexPath is called for both tables
self.searchController.delegate = self;
self.searchController.dimsBackgroundDuringPresentation = NO; // default is YES
self.searchController.searchBar.delegate = self; // so we can monitor text changes + others

// Search is now just presenting a view controller. As such, the normal view controller
// presentation semantics apply. Namely, that presentation will walk up the view controller
// hierarchy until it finds the root view controller or one that defines a presentation context.
//
self.definesPresentationContext = YES;  // know where you want UISearchController to be displayed

// Hides search bar initially. When the user pulls down on the list, the search bar is revealed.
[self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height)];


来源: stackexchange

问:
NSURLCache cachedresponseforrequest no data
why the responseCache is nil? i'd run this post and really get the responseObject from cache. How can i get the responseCache?</p>

```<code>manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];

manager.requestSerializer.cachePolicy=NSURLRequestReturnCacheDataElseLoad;

[manager POST:URL parameters:paramdic progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

    NSData * data=[NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];

    NSURLCache * cache=[NSURLCache sharedURLCache];

    NSCachedURLResponse * responseCache=[cache cachedResponseForRequest:task.originalRequest];

    NSCachedURLResponse * response=[[NSCachedURLResponse alloc]initWithResponse:task.response data:data userInfo:nil storagePolicy:NSURLCacheStorageAllowed];

    [cache storeCachedResponse:response forRequest:task.originalRequest];

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"%@",error);
}];
</code>```

答:
There are three reasons it is nil at that point:

POST requests are not cached by any iOS/OS X networking code because they are not guaranteed to be idempotent (i.e. they can have side effects, such as storing data on the server).  The only way a POST request will ever get stored in an NSURLCache is if you explicitly add it.

POST requests are not cached because NSURLCache uses the URL as the lookup key.  Because the URL does not (cannot) include the POST body, any POST operations to the same URL would be returned for a different POST request, which is almost certainly not what you would want.  So if you do add it, you'll have to add some custom rewriting of the URL on its way into the cache and custom lookup code to make the URLs unique enough based on specific POST body fields or whatever.

The cache is highly asynchronous, so cached data would not necessarily be available when the request's completion handler runs even if this were a GET request.

This is not necessarily a complete set of reasons.  :-)

The cache is intended to reduce network traffic.  You shouldn't generally consult it yourself.  The normal lookup path used by NSURLSession et al performs checks for certain protocol caching policies (e.g. response expiration) that would not be performed by merely asking the cache if it has a response for a particular key.

If you need a general mechanism for storing a single response for later use by your app (rather than keeping it in memory), you should do so in your own internal dictionary (or, if the response is large, by using a download task and moving the file into a temporary folder in your app's sandbox that you purge on every launch).

ContentLicense: CC BY-SA 3.0

Body:
why the responseCache is nil? i'd run this post and really get the responseObject from cache. How can i get the responseCache?

manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];

manager.requestSerializer.cachePolicy=NSURLRequestReturnCacheDataElseLoad;

[manager POST:URL parameters:paramdic progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

    NSData * data=[NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];

    NSURLCache * cache=[NSURLCache sharedURLCache];

    NSCachedURLResponse * responseCache=[cache cachedResponseForRequest:task.originalRequest];

    NSCachedURLResponse * response=[[NSCachedURLResponse alloc]initWithResponse:task.response data:data userInfo:nil storagePolicy:NSURLCacheStorageAllowed];

    [cache storeCachedResponse:response forRequest:task.originalRequest];

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"%@",error);
}];


问:
Pass GeckoFX DOM elements to JavaScript navigation calls
using GeckoFX web browser, is it possible to pass a GeckoElement through JavaScript like this,

```<code>WebBrowser.Navigate("javascript:void("+ele.DomObject+".onclick())");
</code>```

I'm selecting the DOM element through JavaScript (this works fine) atm, but i have the element in c#.

答:
Unfortunately elements can't be passed to javascript like that.

However, the WebBrowser.Navigate call is unnecessary and causes an unneeded loss of page variables.

For the sake of completeness I've posted a snippet - long winded for this occasion ;) - that injects javascript and then calls it from an automated button click via a button.click() handler without the need to navigate the browser to run it all.

```<code>DOM.GeckoScriptElement script = Document.CreateElement("script").AsScriptElement();
script.Type = "text/javascript";
script.Text = "function doAlert(){ alert('My alert - fired by automating a button click on the [Automated Button]'); }";
Document.Body.AppendChild(script);

script = Document.CreateElement("script").AsScriptElement();
script.Type = "text/javascript";
script.Text = "function callDoAlert(id){ var el = document.getElementById(id); el.click(); }";
Document.Body.AppendChild(script);

DOM.GeckoInputElement button = Document.CreateElement("input").AsInputElement();
button.Type = "button";
button.Id = "myButton";
button.Value = "Automated Button";
button.SetAttribute("onclick", "javascript:doAlert();");

Document.Body.AppendChild(button);

DOM.GeckoInputElement button2 = Document.CreateElement("input").AsInputElement();
button2.Type = "button";
button2.Id = "myOtherButton";
button2.Value = "Press Me";
button2.SetAttribute("onclick", "javascript:document.getElementById('myButton').click();");

Document.Body.AppendChild(button2);

//uncomment to fully automate without the <webbrowser>.Navigate("javascript:.."); hack
//button2.click();
</code>```

I'm not sure this snippet will help you, directly, as it's mainly focused on using the GFXe build of the control but, I'm sure it will point you in a better direction than the

WebBrowser.Navigate("javascript:hack.goesHere()"); trick.

ContentLicense: CC BY-SA 2.5

Body:
using GeckoFX web browser, is it possible to pass a GeckoElement through JavaScript like this,

WebBrowser.Navigate("javascript:void("+ele.DomObject+".onclick())");

I'm selecting the DOM element through JavaScript (this works fine) atm, but i have the element in c#.

Body:
Unfortunately elements can't be passed to javascript like that.

However, the WebBrowser.Navigate call is unnecessary and causes an unneeded loss of page variables.

For the sake of completeness I've posted a snippet - long winded for this occasion ;) - that injects javascript and then calls it from an automated button click via a button.click() handler without the need to navigate the browser to run it all.

DOM.GeckoScriptElement script = Document.CreateElement("script").AsScriptElement();
script.Type = "text/javascript";
script.Text = "function doAlert(){ alert('My alert - fired by automating a button click on the [Automated Button]'); }";
Document.Body.AppendChild(script);

script = Document.CreateElement("script").AsScriptElement();
script.Type = "text/javascript";
script.Text = "function callDoAlert(id){ var el = document.getElementById(id); el.click(); }";
Document.Body.AppendChild(script);

DOM.GeckoInputElement button = Document.CreateElement("input").AsInputElement();
button.Type = "button";
button.Id = "myButton";
button.Value = "Automated Button";
button.SetAttribute("onclick", "javascript:doAlert();");

Document.Body.AppendChild(button);

DOM.GeckoInputElement button2 = Document.CreateElement("input").AsInputElement();
button2.Type = "button";
button2.Id = "myOtherButton";
button2.Value = "Press Me";
button2.SetAttribute("onclick", "javascript:document.getElementById('myButton').click();");

Document.Body.AppendChild(button2);

//uncomment to fully automate without the <webbrowser>.Navigate("javascript:.."); hack
//button2.click();

I'm not sure this snippet will help you, directly, as it's mainly focused on using the GFXe build of the control but, I'm sure it will point you in a better direction than the

WebBrowser.Navigate("javascript:hack.goesHere()"); trick.


问:
LU decomposition with PartialPivLU
I have the following code in MATLAB that does an LU decomposition before trying to calculate lamb which I've included to give some context.

```<code>P=[1,2,3;4,5,6;7,8,9];
U=[0;1;2];
[F,J]=lu(P);
Jlamda=F\U;
lamb=J\Jlamda;
</code>```

F is:

0.142857142857143   1                   0
0.571428571428571   0.500000000000000   1
1                   0                   0
```
<p>U is:</p>
<pre class="lang-none prettyprint-override"><code>7                   8                   9
0                   0.857142857142857   1.71428571428571
0                   0                   1.11022302462516e-16
</code>```

When I try to replicate this in Eigen with the following code:

```<code>MatrixXd P(3, 3);
P << 1, 2, 3, 4, 5, 6, 7, 8, 9;
MatrixXd U(3, 1);
U << 0, 1, 2;

PartialPivLU<MatrixXd> lu = PartialPivLU<MatrixXd>(P);
MatrixXd J = lu.matrixLU().triangularView<UpLoType::Upper>();
MatrixXd F = lu.matrixLU().triangularView<UpLoType::UnitLower>();

MatrixXd Jlamda = F.lu().solve(U);
MatrixXd l = J.lu().solve(Jlamda);

cout << F << endl;
cout << endl;
cout << J << endl;
</code>```

Which prints:

1                    0                  0
0.142857             1                  0
0.571429             0.5                1
```
<pre class="lang-none prettyprint-override"><code>7                    8                  9
0                    0.857143           1.71429
0                    0                  1.11022e-16
</code>```

Whilst I can obviously handcraft a matrix to transform the rows of F in C++ to that of the F from MATLAB I am not sure how to do that dynamically.

Is PartialPivLU the best way to go about this, or am I missing something more trivial?

答:
By calling [F,J]=lu(P), the resulting matrix F is a permuted lower triangular matrix. You can call the function as [F,J,perm]=lu(P) to receive F as a truly lower triangle matrix and P as the separate permutation matrix so that F*J = perm*P. By default, the line

MatrixXd F = lu.matrixLU().triangularView<UpLoType::UnitLower>();

using Eigen returns the true lower triangular matrix. If you want the permuted lower triangular matrix like Matlab returns, then you can store the permutation matrix in Eigen by calling permutationP and then multiplying this matrix by F.

ContentLicense: CC BY-SA 4.0

Title: LU decomposition with PartialPivLU

Body:
I have the following code in MATLAB that does an LU decomposition before trying to calculate lamb which I've included to give some context.

P=[1,2,3;4,5,6;7,8,9];
U=[0;1;2];
[F,J]=lu(P);
Jlamda=F\U;
lamb=J\Jlamda;

F is:

0.142857142857143   1                   0
0.571428571428571   0.500000000000000   1
1                   0                   0

U is:

7                   8                   9
0                   0.857142857142857   1.71428571428571
0                   0                   1.11022302462516e-16

When I try to replicate this in Eigen with the following code:

MatrixXd P(3, 3);
P << 1, 2, 3, 4, 5, 6, 7, 8, 9;
MatrixXd U(3, 1);
U << 0, 1, 2;

PartialPivLU<MatrixXd> lu = PartialPivLU<MatrixXd>(P);
MatrixXd J = lu.matrixLU().triangularView<UpLoType::Upper>();
MatrixXd F = lu.matrixLU().triangularView<UpLoType::UnitLower>();

MatrixXd Jlamda = F.lu().solve(U);
MatrixXd l = J.lu().solve(Jlamda);

cout << F << endl;
cout << endl;
cout << J << endl;

Which prints:

1                    0                  0
0.142857             1                  0
0.571429             0.5                1

7                    8                  9
0                    0.857143           1.71429
0                    0                  1.11022e-16

Whilst I can obviously handcraft a matrix to transform the rows of F in C++ to that of the F from MATLAB I am not sure how to do that dynamically.

Is PartialPivLU the best way to go about this, or am I missing something more trivial?


问:
Android VideoView crop_center
I have a RelativeLayout

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center"
    android:foregroundGravity="center"
    android:gravity="center"
    android:orientation="horizontal" >

    <VideoView
        android:id="@+id/videoViewPanel"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:layout_centerInParent="true"/>

</RelativeLayout>
</code>```

And what I need is to show video fullscreen cropped. If I could compare to ImageView, I need to show it as crop_center.

How can I make VideoView not to auto-resize video to fit center, but crop center?

答:
To crop center in fullscreen you can still use a VideoView. Set the VideoView width and height to match the parent inside a RelativeLayout and adjust it to be bigger than the screen and set his position.

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rootLayout"
tools:context="com.example.Activity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_height="match_parent">

        <VideoView
            android:id="@+id/video_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerInParent="true"
            android:layout_centerVertical="true" />

    </RelativeLayout>
</RelativeLayout>
</code>```

And then in onCreate:

```<code>   RelativeLayout rootView=(RelativeLayout) findViewById(R.id.rootLayout);
    Display display=getWindowManager().getDefaultDisplay();
    Point size=new Point();
    display.getSize(size);

    FrameLayout.LayoutParams rootViewParams = (FrameLayout.LayoutParams) rootView.getLayoutParams();
    int videoWidth=864;
    int videoHeight=1280;

    if ((float)videoWidth/(float)videoHeight<(float)size.x/(float)size.y) {
        rootViewParams.width=size.x;
        rootViewParams.height=videoHeight*size.x/videoWidth;
        rootView.setX(0);
        rootView.setY((rootViewParams.height-size.y)/2*-1);
    } else {
        rootViewParams.width=videoWidth*size.y/videoHeight;
        rootViewParams.height=size.y;
        rootView.setX((rootViewParams.width-size.x)/2*-1);
        rootView.setY(0);
    }
    rootView.setLayoutParams(rootViewParams);

    final VideoView mVideoView=(VideoView)findViewById(R.id.video_view);
    mVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.splash));
    mVideoView.requestFocus();

    mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            mVideoView.start();
        }
    });
</code>```

Title: Android VideoView crop_center

Body:
I have a RelativeLayout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center"
    android:foregroundGravity="center"
    android:gravity="center"
    android:orientation="horizontal" >

    <VideoView
        android:id="@+id/videoViewPanel"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:layout_centerInParent="true"/>

</RelativeLayout>

And what I need is to show video fullscreen cropped. If I could compare to ImageView, I need to show it as crop_center.

How can I make VideoView not to auto-resize video to fit center, but crop center?

Body:
To crop center in fullscreen you can still use a VideoView. Set the VideoView width and height to match the parent inside a RelativeLayout and adjust it to be bigger than the screen and set his position.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rootLayout"
tools:context="com.example.Activity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_height="match_parent">

        <VideoView
            android:id="@+id/video_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerInParent="true"
            android:layout_centerVertical="true" />

    </RelativeLayout>
</RelativeLayout>

And then in onCreate:

   RelativeLayout rootView=(RelativeLayout) findViewById(R.id.rootLayout);
    Display display=getWindowManager().getDefaultDisplay();
    Point size=new Point();
    display.getSize(size);

    FrameLayout.LayoutParams rootViewParams = (FrameLayout.LayoutParams) rootView.getLayoutParams();
    int videoWidth=864;
    int videoHeight=1280;

    if ((float)videoWidth/(float)videoHeight<(float)size.x/(float)size.y) {
        rootViewParams.width=size.x;
        rootViewParams.height=videoHeight*size.x/videoWidth;
        rootView.setX(0);
        rootView.setY((rootViewParams.height-size.y)/2*-1);
    } else {
        rootViewParams.width=videoWidth*size.y/videoHeight;
        rootViewParams.height=size.y;
        rootView.setX((rootViewParams.width-size.x)/2*-1);
        rootView.setY(0);
    }
    rootView.setLayoutParams(rootViewParams);

    final VideoView mVideoView=(VideoView)findViewById(R.id.video_view);
    mVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.splash));
    mVideoView.requestFocus();

    mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            mVideoView.start();
        }
    });


问:
youtube-iframe-api remove suggestion thumbnails at bottom of video
Could somebody tell me how to remove youtube suggestion thumbnails on embedded video.

I am using iframe api. It feel like it should be easy. But i just can't find anything on google on how to do it.

tag.src = "https://www.youtube.com/iframe_api";
function initPLayer(playerDivId){
  return new YT.Player(playerDivId, {
    height: '390',
    width: '640',
    videoId: '4EDMR75lrKY',
    events: {
      'onReady': onPlayerReady1,
      'onStateChange': onPlayerStateChangePlayer1
    }
  });
}

Thanks for help!

答:
I knew it was obvious :P.

There is thing called player parameters.
Rel:
This parameter indicates whether the player should show related videos when playback of the initial video ends. Supported values are 0 and 1. The default value is 1.


问:
Set display style for all ToolStripItems
I am attempting to create a toolstrip class that inherits from the system.windows.forms.toolstrip class but specifies the styling to make consistent across our applications.  The individual buttons that get added to the toolstrip have a displaystyle property that specify if you want to display an imageonly, textonly, or both.  Is there a way I can specify the displaystyle for all buttons to be used in my toolstrip?  I'd like to set it in my toolstrip class and have it applied across all applications rather than having to set this in every application.</p>

答:
Create a WindowsFormsControlLibrary project in your solution (for example "ConsistentControls"). Define a class (for example "ConsistentToolStripButton"). Define its capabilities like this.

```<code>using System;
using System.Windows.Forms;

namespace ConsistentControls
{
    public class ConsistentToolStripButton : ToolStripButton
    {
        public override System.Windows.Forms.ToolStripItemDisplayStyle DisplayStyle
        {
            get
            {
                return base.DisplayStyle;
            }
            set
            {

            }
        }

        public ConsistentToolStripButton()
        {
            base.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
        }
    }
}
</code>```

Now you can use this class in, for example "WindowsFormsApplication1", "WindowsFormsApplication2", "WindowsFormsApplication3" and so on...

Here is a screenshot of Design-Time development

Body:
Create a WindowsFormsControlLibrary project in your solution (for example "ConsistentControls"). Define a class (for example "ConsistentToolStripButton"). Define its capabilities like this.

using System;
using System.Windows.Forms;

namespace ConsistentControls
{
    public class ConsistentToolStripButton : ToolStripButton
    {
        public override System.Windows.Forms.ToolStripItemDisplayStyle DisplayStyle
        {
            get
            {
                return base.DisplayStyle;
            }
            set
            {

            }
        }

        public ConsistentToolStripButton()
        {
            base.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
        }
    }
}

Now you can use this class in, for example "WindowsFormsApplication1", "WindowsFormsApplication2", "WindowsFormsApplication3" and so on...

Here is a screenshot of Design-Time development


问:
Why position of div is affected by margin-top of its child?
Here is my markup

CSS

```<code>body{
    background-color:#353535;
}
#parent{
    background-color:#eee;
}
#child{
    background-color:#1b1b1b;
    margin:60px auto 10px;
    width:100px;
}
</code>```

HTML

```<code><div id="parent">
    <div id="child">child</div>
</div>
</code>```

Result: http://jsfiddle.net/W74TZ/

答:
Margin collapsing rules. If the margin-top reaches the top of the  without anything conflicting ( like a padding-top:1px on #parent ) then the parent will "inherit" that.

You can avoid this by setting a padding-top:60px on #parent instead.

Body:
Here is my markup

CSS

body{
    background-color:#353535;
}
#parent{
    background-color:#eee;
}
#child{
    background-color:#1b1b1b;
    margin:60px auto 10px;
    width:100px;
}

HTML

child

Result: http://jsfiddle.net/W74TZ/

Body:
Margin collapsing rules. If the margin-top reaches the top of the <body> without anything conflicting ( like a padding-top:1px on #parent ) then the parent will "inherit" that.

You can avoid this by setting a padding-top:60px on #parent instead.


问:
How to create a DataFrame in Pandas
I am using the playerStat.csv which includes 8 columns from which I only need 2. So I`m trying to create a new DataFrame with only those 2 columns.

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dataset = pd.read_csv("HLTVData/playerStats.csv")
dataset.head(20)
</code>```

I only need the ADR and the Rating.

So I first create a matrix with the data set.

```<code>mat = dataset.as_matrix()
#4 is the ADR and 6 is the Rating
newDAtaSet = pd.DataFrame(dataset, index=indexMatrix,columns=(mat[:,4],mat[:,6]) )
</code>```

But it didn`t work, it threw an exception

```<code>NameError                                 Traceback (most recent call last)
<ipython-input-10-1f975cc2514a> in <module>()
      1 #4 is the ADR and 6 is the Rating
----> 2 newDataSet  = pd.DataFrame(dataset, index=indexMatrix,columns=(mat[:,4],mat[:,6]) )

NameError: name 'indexMatrix' is not defined
</code>```

I also tried using the dataset.

```<code>newDataSet = pd.DataFrame(dataset, index=np.array(range(dataset.shape[0])), columns=dataset['ADR'])

/home/tensor/miniconda3/envs/tensorflow35openvc/lib/python3.5/site-packages/pandas/core/internals.py in _make_na_block(self, placement, fill_value)
   3984
   3985         dtype, fill_value = infer_dtype_from_scalar(fill_value)
-> 3986         block_values = np.empty(block_shape, dtype=dtype)
   3987         block_values.fill(fill_value)
   3988         return make_block(block_values, placement=placement)

MemoryError:
</code>```

答:
I think you need parameter usecols in read_csv:

```<code>dataset = pd.read_csv("HLTVData/playerStats.csv", usecols=['ADR','Rating'])
</code>```

Or:

```<code>dataset = pd.read_csv("HLTVData/playerStats.csv", usecols=[4,6])
</code>```

Title: How to create a DataFrame in Pandas

Body:
I am using the playerStat.csv which includes 8 columns from which I only need 2. So I`m trying to create a new DataFrame with only those 2 columns.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dataset = pd.read_csv("HLTVData/playerStats.csv")
dataset.head(20)

I only need the ADR and the Rating.

So I first create a matrix with the data set.

mat = dataset.as_matrix()
#4 is the ADR and 6 is the Rating
newDAtaSet = pd.DataFrame(dataset, index=indexMatrix,columns=(mat[:,4],mat[:,6]) )

But it didn`t work, it threw an exception

NameError                                 Traceback (most recent call last)
<ipython-input-10-1f975cc2514a> in <module>()
      1 #4 is the ADR and 6 is the Rating
----> 2 newDataSet  = pd.DataFrame(dataset, index=indexMatrix,columns=(mat[:,4],mat[:,6]) )

NameError: name 'indexMatrix' is not defined

I also tried using the dataset.

newDataSet = pd.DataFrame(dataset, index=np.array(range(dataset.shape[0])), columns=dataset['ADR'])

/home/tensor/miniconda3/envs/tensorflow35openvc/lib/python3.5/site-packages/pandas/core/internals.py in _make_na_block(self, placement, fill_value)
   3984
   3985         dtype, fill_value = infer_dtype_from_scalar(fill_value)
-> 3986         block_values = np.empty(block_shape, dtype=dtype)
   3987         block_values.fill(fill_value)
   3988         return make_block(block_values, placement=placement)

MemoryError:

Body:
I think you need parameter usecols in read_csv:

dataset = pd.read_csv("HLTVData/playerStats.csv", usecols=['ADR','Rating'])

Or:

dataset = pd.read_csv("HLTVData/playerStats.csv", usecols=[4,6])


问:
Application is not loading after upgrading to payara 4.1.1.171
Upgraded server from glassfish 3.1 to payara 4.1.1.171, took the glassfish config backup and restored to payara 4.1.1.171. After that my application is not loading and in console it throws this error net::ERR_INCOMPLETE_CHUNKED_ENCODING

If i change the compression attribute to 'off' then application is loading .

```<code><http request-timeout-seconds="2700" chunking-enabled="false" compressable-mime-type="text/html,text/xml,text/plain,image/gif,image/jpeg,image/png,text/css,text/javascript,application/json,application/xml" max-connections="250" compression="on" default-virtual-server="server">
</code>```

In the above configuration if i change the compression="on" to compression="off" then its working fine.
Don't why this is breaking in payara which was working in glassfish with same setting. I can't turn off the compression which will saves the bandwidth.

Note: Already some issues are reported similar to this Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error
but this is not case for me

答:
The issue should be fixed in Payara 4.1.2.172 according to this issue
Use that version instead of 4.1.1.171</p>

Body:
Upgraded server from glassfish 3.1 to payara 4.1.1.171, took the glassfish config backup and restored to payara 4.1.1.171. After that my application is not loading and in console it throws this error net::ERR_INCOMPLETE_CHUNKED_ENCODING

If i change the compression attribute to 'off' then application is loading .

<http request-timeout-seconds="2700" chunking-enabled="false" compressable-mime-type="text/html,text/xml,text/plain,image/gif,image/jpeg,image/png,text/css,text/javascript,application/json,application/xml" max-connections="250" compression="on" default-virtual-server="server">

In the above configuration if i change the compression="on" to compression="off" then its working fine.
Don't why this is breaking in payara which was working in glassfish with same setting. I can't turn off the compression which will saves the bandwidth.

Note: Already some issues are reported similar to this Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error
but this is not case for me


问:
Python Binomial Coefficient

```<code>import math
x = int(input("Enter a value for x: "))
y = int(input("Enter a value for y: "))

if y == 1 or y == x:
    print(1)

if y > x:
    print(0)
else:
    a = math.factorial(x)
    b = math.factorial(y)
    div = a // (b*(x-y))
    print(div)
</code>```

This binomial coefficient program works but when I input two of the same number which is supposed to equal to 1 or when y is greater than x it is supposed to equal to 0.

答:
For Python 3, scipy has the function scipy.special.comb, which may produce floating point as well as exact integer results

```<code>import scipy.special

res = scipy.special.comb(x, y, exact=True)
</code>```

See the documentation for scipy.special.comb.

For Python 2, the function is located in scipy.misc, and it works the same way:

```<code>import scipy.misc

res = scipy.misc.comb(x, y, exact=True)
</code>```

Title: Python Binomial Coefficient

Body:
import math
x = int(input("Enter a value for x: "))
y = int(input("Enter a value for y: "))

if y == 1 or y == x:
    print(1)

if y > x:
    print(0)
else:
    a = math.factorial(x)
    b = math.factorial(y)
    div = a // (b*(x-y))
    print(div)

This binomial coefficient program works but when I input two of the same number which is supposed to equal to 1 or when y is greater than x it is supposed to equal to 0.

Body:
For Python 3, scipy has the function scipy.special.comb, which may produce floating point as well as exact integer results

import scipy.special

res = scipy.special.comb(x, y, exact=True)

See the documentation for scipy.special.comb.

For Python 2, the function is located in scipy.misc, and it works the same way:

import scipy.misc

res = scipy.misc.comb(x, y, exact=True)


问:
Woocommerce - How to hide trailing zeros after the 2nd decimal place?

So I have a question I was hoping somebody might be able to help me out with...
 I have a WordPress website that uses WooCommerce and I'm trying to do something relatively specific. The site has a fair deal of bulk pricing discounts for various products.
Now when it comes to the bulk pricing I kind of need the calculations to be done with four decimal places (i.e. $0.1234), So I have the WooCommerce settings set so that the number of decimals is 4.
The thing is, that on a lot of our products we don't have bulk pricing discounts; in most of these cases the four decimal places are completely unnecessary. (For example: $0.5500 or $12.0000) Is there any way I can trim the trailing the zeros but only if it is after the second decimal place?
For example, if I had $0.5500 it would be displayed as $0.55 and if I had $12.0000 it would be displayed as $12.00

I know a very similar question was asked a few years ago (see here), but unfortunately, the answer that worked in that case does not seem to work for me... That being said, I could be trying to use it the wrong way. I am not very familiar with using regular expressions in a WordPress "functions.php" file.

Any help at all would be greatly appreciated! Thanks!

Edit:

At this point I have something along the lines of:

```<code>add_action('wc_price', 'custom_price_disp');
function custom_price_disp($price) {
    $count = null;
    $resultingPrice = preg_replace('/(?<=\d{2})(0+)$/', '', $price, -1, $count);
    return $resultingPrice;
}
</code>```

But this code does not seem to work. Prices are still displayed the same as they were before.

答:
I’ve not used it myself, but based on the aforementioned wc_price() method’s code, it looks like you can take advantage of a filter:

```<code>if ( apply_filters( 'woocommerce_price_trim_zeros', false ) && $decimals > 0 ) {
  $price = wc_trim_zeros( $price );
}
</code>```

You should be able to add this to your functions.php:

```<code>add_filter( 'woocommerce_price_trim_zeros', true );
</code>```

To trigger this behavior.

Body:
So I have a question I was hoping somebody might be able to help me out with...
 I have a WordPress website that uses WooCommerce and I'm trying to do something relatively specific. The site has a fair deal of bulk pricing discounts for various products.
Now when it comes to the bulk pricing I kind of need the calculations to be done with four decimal places (i.e. $0.1234), So I have the WooCommerce settings set so that the number of decimals is 4.
The thing is, that on a lot of our products we don't have bulk pricing discounts; in most of these cases the four decimal places are completely unnecessary. (For example: $0.5500 or $12.0000) Is there any way I can trim the trailing the zeros but only if it is after the second decimal place?
For example, if I had $0.5500 it would be displayed as $0.55 and if I had $12.0000 it would be displayed as $12.00

I know a very similar question was asked a few years ago (see here), but unfortunately, the answer that worked in that case does not seem to work for me... That being said, I could be trying to use it the wrong way. I am not very familiar with using regular expressions in a WordPress "functions.php" file.

Any help at all would be greatly appreciated! Thanks!

Edit:

At this point I have something along the lines of:

add_action('wc_price', 'custom_price_disp');
function custom_price_disp($price) {
    $count = null;
    $resultingPrice = preg_replace('/(?<=\d{2})(0+)$/', '', $price, -1, $count);
    return $resultingPrice;
}

But this code does not seem to work. Prices are still displayed the same as they were before.

Body:
I’ve not used it myself, but based on the aforementioned wc_price() method’s code, it looks like you can take advantage of a filter:

if ( apply_filters( 'woocommerce_price_trim_zeros', false ) && $decimals > 0 ) {
  $price = wc_trim_zeros( $price );
}

You should be able to add this to your functions.php:

add_filter( 'woocommerce_price_trim_zeros', true );

To trigger this behavior.


问:
saml2 application not supported
In my company we're setting up SAML2 SSO for all applications. One application (ARIS Publisher Server) do not support SAML but only Kerberos.

In this case, what should we do to set up SAML2 SSO for this application ?

In advance, thank you for your help !

Zack

答:
You need to add a SAML client side stack to the application.

There's a list here - SAML : SAML connectivity / toolkit .

The other option is to deliver this out of an IDaaS product e.g. Auth0, Okta etc.

Title: saml2 application not supported


问:
check if a number is present in a list, app engine templates
I am trying to generate a board (10X10) using the app engine templates and html table. So this means basically putting a break after 10 iterations of the loop. How can I acieve this using the app engine's inbuilt template engine (django 0.96)?

Update

Lukes answer solved my problem of automatically inserting the break.

But I still need to find a way to check for each number if it is present in a list and give it a specific class. Is there any way to achieve something like this:

```<code>{% for number in list }
  <td {% if number in another_list %}class="special"{% endif %}>{{number}}</td>
{% endfor }
</code>```

答:
Does 0.96's templatetags have divisibleby? That seems like it'd do the trick:</p>

```<code>{% for end_number in end_numbers %}
    {% if forloop.counter|divisibleby:"10" %}
      </tr>
    {% endif %}
{% endfor %}
</code>```

Body:
I am trying to generate a board (10X10) using the app engine templates and html table. So this means basically putting a break after 10 iterations of the loop. How can I acieve this using the app engine's inbuilt template engine (django 0.96)?

Update

Lukes answer solved my problem of automatically inserting the break.

But I still need to find a way to check for each number if it is present in a list and give it a specific class. Is there any way to achieve something like this:

{% for number in list }
  {{number}}
{% endfor }

Body:
Does 0.96's templatetags have divisibleby? That seems like it'd do the trick:

{% for end_number in end_numbers %}
    {% if forloop.counter|divisibleby:"10" %}
      </tr>
    {% endif %}
{% endfor %}


问:
Django 1.11 custom widget template TemplateDoesNotExist
I am trying replace widget template with my own, but I am getting a TemplateDoesNotExist error.

In app\forms.py:

```<code>class SelectPlus(Select):
    template_name = 'selectplus.html'

class SimpleForm(ModelForm):
    somefield = ModelChoiceField(
        queryset=SomeObjects.objects.all(),
        widget=SelectPlus(attrs={'url': 'custom_url_to_context'})
    )
</code>```

In settings.py

```<code>TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [ROOT_PATH, 'templates'],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],

    },
},
</code>```

In debug trace I see that template-loader doesn't search in apps folders or main template folder:

But all other templates works fine.

答:
You have two ways to fix this.

1) fixing your templates path, like this.

```<code>TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [ROOT_PATH, os.path.join(BASE_DIR, 'templates')],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],

    },
}
</code>```

2) Add template folder inside the app.

Body:
I am trying replace widget template with my own, but I am getting a TemplateDoesNotExist error.

In app\forms.py:

class SelectPlus(Select):
    template_name = 'selectplus.html'

class SimpleForm(ModelForm):
    somefield = ModelChoiceField(
        queryset=SomeObjects.objects.all(),
        widget=SelectPlus(attrs={'url': 'custom_url_to_context'})
    )

In settings.py

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [ROOT_PATH, 'templates'],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],

    },
},

In debug trace I see that template-loader doesn't search in apps folders or main template folder:

But all other templates works fine.

Body:
You have two ways to fix this.

1) fixing your templates path, like this.

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [ROOT_PATH, os.path.join(BASE_DIR, 'templates')],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],

    },
}

2) Add template folder inside the app.


问:
How do I install BuildTools 17 and Up in Android Studio?
Android Studio only gives me an option to install Android SDK Build-Tools 26, how do I install for BuildTools 17</p>

答: In SDK Manager, go to SDK Tools tab, click on Show Package Details on the bottom of SDK Manager window. Scroll down and check the versions you want to download.


问:
Getting "incorrect number of arguments to numeric-type constructor" error in a shader
I've been learning Unity shader for couple of days and decided to port this oil shader from Shadertoy.

I get the following error:

incorrect number of arguments to numeric-type constructor at line 69
  (on glcore)

Here is the relevant part of the shader code:

```<code>#define T (_Time/3.+5.)

fixed4 frag(v2f i) : SV_Target
{
    float4 fragColor = 0;
    float2 fragCoord = i.vertex.xy;

    float4 k = fragColor;
    float2 p = fragCoord;

    float s = 1.;

    #define rot(p,a) float2 sc = sin(float2(a,a + 1.6));  p *= float2x2(sc.y,-sc.x,sc);

    #define A float3(0,1,157)
    #define B {float2 m = frac(p),l = dot(p - m,A.yz) + A.xz,r = lerp(frac(57.*sin(l++)),frac(57.*sin(l)),(m *= m*(3. - m - m)).x); k += lerp(r.x,r.y,m.y) / (s += s); p *= float4(1,1,1,-1);}

    p *= log(T) / R.y;              // scaling (slow zoom out)
    p.x += T;                       // translation
    rot(p, T / 22.); //ERROR HERE

    //......the rest of the code below
}
</code>```

The rot(p, T / 22.); line is where the error is at. The funny thing is that when I remove or comment-out this line of code, the shader compiles and is working fine. I still want to know why that line can't compile.

What's causing that error and how can I fix it?

EDIT:

As pointed out by helium, float3x3 is a matrix.

Below is the original rot function:

```<code>#define rot(p,a) vec2 sc=sin(vec2(a,a+1.6)); p*=mat2(sc.y,-sc.x,sc);
</code>```

And the ported version:

```<code>#define rot(p,a) float2 sc = sin(float2(a,a + 1.6));  p *= float2x2(sc.y,-sc.x,sc);
</code>```

Notice how I replaced mat2 with float2x2 because that's the equivalent type in  HLSL.

I do believe that the problem is from float2x2(sc.y,-sc.x,sc);. What is the appropriate way to do this and still use the 3 parameters as the original code did?

答:
The built-in value _Time is a float4 so you have to pick one of the components depending on the time scale you want:

_Time float4 (t/20, t, t*2, t*3), use to animate things inside the shaders.

for example #define T (_Time.y/3.+5.).

Another thing is the * operator for float2x2 represents a component-wise product of 2 matrices. For vector-matrix/matrix-matrix product you should use the mul function.

So in the rot function you should have p =mul(p, float2x2(sc.y,-sc.x,sc));.

For more info on this you can go to: https://en.wikibooks.org/wiki/Cg_Programming/Vector_and_Matrix_Operations.

Body:
I've been learning Unity shader for couple of days and decided to port this oil shader from Shadertoy.

I get the following error:

incorrect number of arguments to numeric-type constructor at line 69
  (on glcore)

Here is the relevant part of the shader code:

#define T (_Time/3.+5.)

fixed4 frag(v2f i) : SV_Target
{
    float4 fragColor = 0;
    float2 fragCoord = i.vertex.xy;

    float4 k = fragColor;
    float2 p = fragCoord;

    float s = 1.;

    #define rot(p,a) float2 sc = sin(float2(a,a + 1.6));  p *= float2x2(sc.y,-sc.x,sc);

    #define A float3(0,1,157)
    #define B {float2 m = frac(p),l = dot(p - m,A.yz) + A.xz,r = lerp(frac(57.*sin(l++)),frac(57.*sin(l)),(m *= m*(3. - m - m)).x); k += lerp(r.x,r.y,m.y) / (s += s); p *= float4(1,1,1,-1);}

    p *= log(T) / R.y;              // scaling (slow zoom out)
    p.x += T;                       // translation
    rot(p, T / 22.); //ERROR HERE

    //......the rest of the code below
}

The rot(p, T / 22.); line is where the error is at. The funny thing is that when I remove or comment-out this line of code, the shader compiles and is working fine. I still want to know why that line can't compile.

What's causing that error and how can I fix it?

EDIT:

As pointed out by helium, float3x3 is a matrix.

Below is the original rot function:

#define rot(p,a) vec2 sc=sin(vec2(a,a+1.6)); p*=mat2(sc.y,-sc.x,sc);

And the ported version:

#define rot(p,a) float2 sc = sin(float2(a,a + 1.6));  p *= float2x2(sc.y,-sc.x,sc);

Notice how I replaced mat2 with float2x2 because that's the equivalent type in  HLSL.

I do believe that the problem is from float2x2(sc.y,-sc.x,sc);. What is the appropriate way to do this and still use the 3 parameters as the original code did?


问:
Microsoft R Server SQL NULL/Missing values
I am having a bit of on issue using RxSqlServerData() in Microsoft R to import a table from a SQL Server database. My database in SQL server contains rows that have both blanks and NULL values. When I run RxSqlServerData, these both get imported as "missing" values, specifically, <NA>

Is there something I can specify in the colInfo argument that could import these as factors, say, "None" or something similar.

Thanks.

答:
So after you have imported the data you can use the rxDataStep function, and in the transforms argument, you define how your missing values should be handled.

An example of this is, where I have a table with some columns and some of the columns have null values or - in the case of string columns - potentially empty string. My table definition looks like so:

```<code>CREATE TABLE dbo.tb_MissingValue(RowID int identity PRIMARY KEY,
                                 Col1 int,
                                 Col2 int,
                                 Col3 varchar(50))
</code>```

And I have inserted data like so:

```<code>INSERT INTO dbo.tb_MissingValue(Col1, Col2, Col3)
VALUES (1, null, 'Hello'),
        (null, 2, 'world'),
        (3, 1, ''),
        (4, 2, 'Again');
</code>```

My R code looks like this to retrieve the data from the database:

```<code>connString <- "Driver=SQL Server;
               Server=win10-dev;
               Database=RTest;
               Uid=sa;
               Pwd=secret_stuff"

missingData <- RxSqlServerData(connectionString = connString,
                 sqlQuery = "SELECT * FROM dbo.tb_MissingValue")
</code>```

Looking at the data in the missingData data frame it looks like so:

```<code>  RowID Col1 Col2  Col3
  1     1    1   NA Hello
  2     2   NA    2 world
  3     3    3    1  <NA>
  4     4    4    2 Again
</code>```

At this stage what I can do is to use the rxDataStep function and the transforms argument, like I mentioned above:

```<code>nonMissing <- rxDataStep(inData = missingData,
                     transforms = list(
                     Col1 = ifelse(is.na(Col1), "Missing", Col1),
                     Col2 = ifelse(is.na(Col2), "Missing", Col2),
                     Col3 = ifelse(is.na(Col3), "Missing", Col3)))
</code>```

Then when I view the data nonMissing, I get this:

```<code>  RowID    Col1    Col2    Col3
  1     1       1 Missing   Hello
  2     2 Missing       2   world
  3     3       3       1 Missing
  4     4       4       2   Again
</code>```

You could of course also handle the missing values in your original query. That's probably what I'd do.

Hope this helps!

Niels

Body:
So after you have imported the data you can use the rxDataStep function, and in the transforms argument, you define how your missing values should be handled.

An example of this is, where I have a table with some columns and some of the columns have null values or - in the case of string columns - potentially empty string. My table definition looks like so:

CREATE TABLE dbo.tb_MissingValue(RowID int identity PRIMARY KEY,
                                 Col1 int,
                                 Col2 int,
                                 Col3 varchar(50))

And I have inserted data like so:

INSERT INTO dbo.tb_MissingValue(Col1, Col2, Col3)
VALUES (1, null, 'Hello'),
        (null, 2, 'world'),
        (3, 1, ''),
        (4, 2, 'Again');

My R code looks like this to retrieve the data from the database:

connString <- "Driver=SQL Server;
               Server=win10-dev;
               Database=RTest;
               Uid=sa;
               Pwd=secret_stuff"

missingData <- RxSqlServerData(connectionString = connString,
                 sqlQuery = "SELECT * FROM dbo.tb_MissingValue")

Looking at the data in the missingData data frame it looks like so:

  RowID Col1 Col2  Col3
  1     1    1   NA Hello
  2     2   NA    2 world
  3     3    3    1  <NA>
  4     4    4    2 Again

At this stage what I can do is to use the rxDataStep function and the transforms argument, like I mentioned above:

nonMissing <- rxDataStep(inData = missingData,
                     transforms = list(
                     Col1 = ifelse(is.na(Col1), "Missing", Col1),
                     Col2 = ifelse(is.na(Col2), "Missing", Col2),
                     Col3 = ifelse(is.na(Col3), "Missing", Col3)))

Then when I view the data nonMissing, I get this:

  RowID    Col1    Col2    Col3
  1     1       1 Missing   Hello
  2     2 Missing       2   world
  3     3       3       1 Missing
  4     4       4       2   Again

You could of course also handle the missing values in your original query. That's probably what I'd do.

Hope this helps!

Niels


问:
Automatic loading of Excel add-ins with Add-in Commands
As mentioned here (https://dev.office.com/blogs/make-your-add-ins-available-in-the-office-ribbon) all new taskpane submissions to the Office store must use commands to pass validation.

After experimentation with add-ins with and without commands, it appears that existing add-ins without commands will automatically reload when the file is re-opened in Excel online (e.g. via OneDrive, Dropbox).  Add-ins with commands do not reload upon re-opening the file, and must be re-installed through the add-in store each time the file is opened.

I know there have been similar questions asked here:

Online Excel Add In on workbook re-opening

Automatically loading Word Task Pane Office Add-in

Keep Office add-in task pane open at document load

And perhaps more specifically here:

Office Web App - Show task pane on load where the suggestion is to remove add-in commands.

Given that I cannot submit an add-in without add-in commands any more, how can I have the add-in persist / show up in the ribbon on subsequent re-opening of the file (currently our add-in users have to constantly re-install the add-in) ?

答: There is now a topic about this: Automatically open a task pane with a document. And a sample at: Office OOXML EmbedAddin</p>


问:
Fused Location Provider class not found despite Google Play Services dependency in gradle file
My app uses the FusedLocationProviderApi for getting the current location. I've already put the line which allows the app to use Google Play Services in the gradle file for my app module:

```<code>compile 'com.google.android.gms:play-services-ads:11.0.2'
</code>```

But when I try to declare a FusedLocationProvider variable, it turns red and does not recognize the class. My only guess is that I should probably import the class, but I don't know exactly how.

答:
You are currently only importing the ads API.

In addition to the ads compile line, you will need to add this to your build.gradle:

```<code>implementation 'com.google.android.gms:play-services-location:16.0.0'
</code>```

To see the current breakdown of individual APIs, take a look at the documentation: https://developers.google.com/android/guides/setup

Body:
My app uses the FusedLocationProviderApi for getting the current location. I've already put the line which allows the app to use Google Play Services in the gradle file for my app module:

compile 'com.google.android.gms:play-services-ads:11.0.2'

But when I try to declare a FusedLocationProvider variable, it turns red and does not recognize the class. My only guess is that I should probably import the class, but I don't know exactly how.

Body:
You are currently only importing the ads API.

In addition to the ads compile line, you will need to add this to your build.gradle:

implementation 'com.google.android.gms:play-services-location:16.0.0'

To see the current breakdown of individual APIs, take a look at the documentation: https://developers.google.com/android/guides/setup


问:
How can I make each section the same height?
I was wondering how I can make each section which is called #app, section2 and section3 the same height which is the full web page 100% like demonstrated in the #app section of my site. For example, I don't want to see the text "PART 3" when I'm at #section2 I want the height to of each section to be the equivalent of a single page.

Here is an example of what I'm trying to achieve.

In order to make them all the same height I used the following CSS however, I'm obviously missing something as it's not working.

```<code>body,
html {
    width: 100%;
    height: 100%;
}

#app
#section2,
#section3,{
  height: 100vh;
  width: 100%;
}
</code>```

Here is a link to my site code using jsfiddle

答:
```<code>#app,
#section2,
#section3 {
  height: 100vh;
  width: 100%;
}
</code>```

Your initial CSS is improperly written so that the above code (corrected) is never properly applied.  Fix that and you're well on your way to achieving your desired results.

Body:
I was wondering how I can make each section which is called #app, section2 and section3 the same height which is the full web page 100% like demonstrated in the #app section of my site. For example, I don't want to see the text "PART 3" when I'm at #section2 I want the height to of each section to be the equivalent of a single page.

Here is an example of what I'm trying to achieve.

In order to make them all the same height I used the following CSS however, I'm obviously missing something as it's not working.

body,
html {
    width: 100%;
    height: 100%;
}

#app
#section2,
#section3,{
  height: 100vh;
  width: 100%;
}

Here is a link to my site code using jsfiddle

Body:
#app,
#section2,
#section3 {
  height: 100vh;
  width: 100%;
}

Your initial CSS is improperly written so that the above code (corrected) is never properly applied.  Fix that and you're well on your way to achieving your desired results.


问:
Can I add a button for Skype for business in my website
I know its easy to add Skype link using https://www.skype.com/en/developer/create-contactme-buttons/ .
But can the similar stuff be done for SkypeForBusiness ?</p>

答:
Creating a link like this works with my employer.

```<code><a href="SIP:user@domain.com">Chat with Skype</a>
</code>```

I didn't see anything useful on the SDK site.

Body:
Creating a link like this works with my employer.

<a href="SIP:user@domain.com">Chat with Skype</a>

I didn't see anything useful on the SDK site.


问:
How can I sort a list numerically from a specific part of a string
I have this list of links that need to be sorted when they are generated on my page.

The links appear like this

"https://www.dropbox.com/s/###/NF%208975%###"
"https://www.dropbox.com/s/###/NF%207600%###"

I then map through them when they are generated onto my page, and create a name based on whats at the end of the link (removing all the junk characters).

Is it possible, without altering the url, to sort them numerically based on the what's at the end of the url. That way when I map through them, they are already ordered.

Like this:

NF%207600%###

NF%208975%###

I've looked through some similar SO questions, but can't seem to find anything relative enough.

答:
You can .map().sort().map(). It may seem bulky, but if you have a lot of URLs, this is more performant since you don't have to perform a number-parsing regex-replace every time you compare a URL to another one. For example, compare the amount of calls when sorting just 5 URLs:

var array = [
  'https://www.dropbox.com/s/###/NF%208975%###',
  'https://www.dropbox.com/s/###/NF%209213%###',
  'https://www.dropbox.com/s/###/NF%205346%###',
  'https://www.dropbox.com/s/###/NF%201764%###',
  'https://www.dropbox.com/s/###/NF%207600%###'
];

function getId(url) {
  return Number(url.replace(/^.*%(\d+)%.*$/, '$1'));
}

function count(func) {
  function wrapper() {
    wrapper.count++;
    return func.apply(this, arguments);
  }

  wrapper.count = 0;

  return wrapper;
}

var countGetId = count(getId);

var sorted = array
  .map(url => ({ url, number: countGetId(url) }))
  .sort((a, b) => a.number - b.number)
  .map(obj => obj.url);

console.log('.map().sort().map()')
console.log(sorted);
console.log('getId called ' + countGetId.count + ' times');

var countGetId = count(getId);

var sorted = array.sort((a, b) => countGetId(a) - countGetId(b))

console.log('.sort()')
console.log(sorted);
console.log('getId called ' + countGetId.count + ' times');```
</div>
</div>
</p>

<p>So, just do this:</p>

```function getId(url) {
  return Number(url.replace(/^.*%(\d+)%.*$/, '$1'));
}

var sorted = array
  .map(url => ({ url, number: getId(url) }))
  .sort((a, b) => a.number - b.number)
  .map(obj => obj.url);

console.log(sorted);
```

Body:
You can .map().sort().map(). It may seem bulky, but if you have a lot of URLs, this is more performant since you don't have to perform a number-parsing regex-replace every time you compare a URL to another one. For example, compare the amount of calls when sorting just 5 URLs:

var array = [
  'https://www.dropbox.com/s/###/NF%208975%###',
  'https://www.dropbox.com/s/###/NF%209213%###',
  'https://www.dropbox.com/s/###/NF%205346%###',
  'https://www.dropbox.com/s/###/NF%201764%###',
  'https://www.dropbox.com/s/###/NF%207600%###'
];

function getId(url) {
  return Number(url.replace(/^.*%(\d+)%.*$/, '$1'));
}

function count(func) {
  function wrapper() {
    wrapper.count++;
    return func.apply(this, arguments);
  }

  wrapper.count = 0;

  return wrapper;
}

var countGetId = count(getId);

var sorted = array
  .map(url => ({ url, number: countGetId(url) }))
  .sort((a, b) => a.number - b.number)
  .map(obj => obj.url);

console.log('.map().sort().map()')
console.log(sorted);
console.log('getId called ' + countGetId.count + ' times');

var countGetId = count(getId);

var sorted = array.sort((a, b) => countGetId(a) - countGetId(b))

console.log('.sort()')
console.log(sorted);
console.log('getId called ' + countGetId.count + ' times');

So, just do this:

function getId(url) {
  return Number(url.replace(/^.*%(\d+)%.*$/, '$1'));
}

var sorted = array
  .map(url => ({ url, number: getId(url) }))
  .sort((a, b) => a.number - b.number)
  .map(obj => obj.url);

console.log(sorted);


问:
The 'EurekaPackage' package did not load correctly - Visual Studio 2013
I installed VS 2013 Premium. On first launch I get this error

Microsoft Visual Studio

The 'EurekaPackage' package did not load correctly.

The problem may have been caused by a configuration change or by the
  installation of another extension. You can get more information by
  examining the file
  '\AppData\Roaming\Microsoft\VisualStudio\12.0\ActivityLog.xml'.

Continue to show this error message? Yes   No

Below a copied from ActivityLog.xml

```<code><entry>
    <record>83</record>
    <time>2014/03/14 14:51:59.561</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Begin package load [File Change Manager Package]</description>
    <guid>{4825B9A3-93E2-4327-9044-41F72EE7E5C9}</guid>
  </entry>
  <entry>
    <record>84</record>
    <time>2014/03/14 14:51:59.577</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>End package load [File Change Manager Package]</description>
    <guid>{4825B9A3-93E2-4327-9044-41F72EE7E5C9}</guid>
  </entry>
  <entry>
    <record>85</record>
    <time>2014/03/14 14:53:21.928</time>
    <type>Error</type>
    <source>VisualStudio</source>
    <description>SetSite failed for package [EurekaPackage]</description>
    <guid>{8C28E535-ABC9-4F92-B5C9-6C16617C8884}</guid>
    <hr>80131509</hr>
    <errorinfo>Cannot create file mapping.</errorinfo>
  </entry>
  <entry>
    <record>86</record>
    <time>2014/03/14 14:53:21.977</time>
    <type>Error</type>
    <source>VisualStudio</source>
    <description>End package load [EurekaPackage]</description>
    <guid>{8C28E535-ABC9-4F92-B5C9-6C16617C8884}</guid>
    <hr>80131509</hr>
    <errorinfo>Cannot create file mapping.</errorinfo>
  </entry>
  <entry>
    <record>2462</record>
    <time>2014/03/14 14:56:57.158</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Entering function CVsPackageInfo::HrInstantiatePackage</description>
    <guid>{ED19932F-5443-4587-A005-1CB9158B2F64}</guid>
  </entry>
</code>```

答:
I got this error in Visual Studio 2017 when trying to load my ASP.NET project. I also got two instances of the error "The PackageManagementPackage did not load correctly" along with the "The 'EurekaPackage' package did not load correctly" error.

Similar to tandrasz's answer, I started seeing this error after disabling a bunch of extensions in Visual Studio's Tools > Extensions and Updates dialog.

I also found that the "Microsoft ASP.NET and Web Tools" extension had become disabled, even though I hadn't manually disabled it.  Even after manually re-enabling that extension, it would become disabled again each time I restarted Visual Studio while the "package did not load correctly" error persisted.

Doing some science of re-enabling one extension at a time and restarting Visual Studio each time, I found that the specific extension I needed to re-enable to get things working again was the Microsoft Azure App Services Tools extension -- even though my project doesn't do anything with Azure.

(I also needed to re-enable the Microsoft ASP.NET and Web Tools extension along with that Azure extension.)

Body:
I installed VS 2013 Premium. On first launch I get this error

Microsoft Visual Studio

The 'EurekaPackage' package did not load correctly.

The problem may have been caused by a configuration change or by the
  installation of another extension. You can get more information by
  examining the file
  '\AppData\Roaming\Microsoft\VisualStudio\12.0\ActivityLog.xml'.

Continue to show this error message? Yes   No

Below a copied from ActivityLog.xml

<entry>
    <record>83</record>
    <time>2014/03/14 14:51:59.561</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Begin package load [File Change Manager Package]</description>
    <guid>{4825B9A3-93E2-4327-9044-41F72EE7E5C9}</guid>
  </entry>
  <entry>
    <record>84</record>
    <time>2014/03/14 14:51:59.577</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>End package load [File Change Manager Package]</description>
    <guid>{4825B9A3-93E2-4327-9044-41F72EE7E5C9}</guid>
  </entry>
  <entry>
    <record>85</record>
    <time>2014/03/14 14:53:21.928</time>
    <type>Error</type>
    <source>VisualStudio</source>
    <description>SetSite failed for package [EurekaPackage]</description>
    <guid>{8C28E535-ABC9-4F92-B5C9-6C16617C8884}</guid>

80131509

    <errorinfo>Cannot create file mapping.</errorinfo>
  </entry>
  <entry>
    <record>86</record>
    <time>2014/03/14 14:53:21.977</time>
    <type>Error</type>
    <source>VisualStudio</source>
    <description>End package load [EurekaPackage]</description>
    <guid>{8C28E535-ABC9-4F92-B5C9-6C16617C8884}</guid>

80131509

    <errorinfo>Cannot create file mapping.</errorinfo>
  </entry>
  <entry>
    <record>2462</record>
    <time>2014/03/14 14:56:57.158</time>
    <type>Information</type>
    <source>VisualStudio</source>
    <description>Entering function CVsPackageInfo::HrInstantiatePackage</description>
    <guid>{ED19932F-5443-4587-A005-1CB9158B2F64}</guid>
  </entry>


答:
You can use regex to extract the number and then compare by it:

var urls = ["https://www.dropbox.com/s/###/NF%208975%###", "https://www.dropbox.com/s/###/NF%207600%###"]

function extract_number(url) {
    return Number(url.replace(/.*%(\d+)%.*/, "$1"))
}

urls.sort(function(a, b) {
    if(extract_number(a) < extract_number(b)) {
        return -1;
    }
    if(extract_number(a) > extract_number(b)) {
        return 1;
    }
    return 0;
})

console.log(urls);```

Title: How can I sort a list numerically from a specific part of a string

Body:
I have this list of links that need to be sorted when they are generated on my page.

The links appear like this

"https://www.dropbox.com/s/###/NF%208975%###"
"https://www.dropbox.com/s/###/NF%207600%###"

I then map through them when they are generated onto my page, and create a name based on whats at the end of the link (removing all the junk characters).

Is it possible, without altering the url, to sort them numerically based on the what's at the end of the url. That way when I map through them, they are already ordered.

Like this:

NF%207600%###

NF%208975%###

I've looked through some similar SO questions, but can't seem to find anything relative enough.


问:
Best way to convert XML to X12 and X12 to XML
Looking for a tool/library to convert XML to X12 (270 - medical eligibility request) and then to convert the X12 response (271 - eligibility response) back to XML.  This will be embedded in a server application (will consider any target language).  I've toyed with idea of writing my own X12 parser and generator but this project will most likely expand to other X12 transactions and I'd like to find a solution that will be extensible.</p>

答:
Look at pyx12.

It includes scripts for X12 to XML and XML to X12.

Why Python?  Because you'll often need to customize X12 documents to handle the allowed variations between payers and providers.

OwnerDisplayName: jdigital


问:
JS: How to compare 2 dates converting from UTC to defined timezone?
I stored a string of UTC Date (without time):

```<code>var limitDateStr = "2017-07-04T00:00:00.000Z";
</code>```

And a TIMEZONE in hours (based on this), not in Zone Name (like America/Antigua)

```<code>var timezone = "-6.0"; //could be from -12.0 to 12.0
</code>```

The problem is: Verify if actual date, is greater than limitDate in the same Timezone.

What I Do with Moment.js

I Used moment for change the timezone, but when y change the offset. The date is changed too:

```<code>  var _expirationDateUTC = moment.utc(limitDateStr).utcOffset(parseFloat(timezone)).format();
  // "2017-07-03T18:00:00-06:00"
</code>```

Instead of 2017-07-04T00:00:00-06:00

Actual date, works great: (except for Days Savings)

```<code>var today = moment.utc().utcOffset(parseFloat(timezone)).format();
//"2017-07-04T15:32:49-06:00"
</code>```

And I want to compare... maybe with moment function:

```<code>today.isAfter(_expirationDateUTC);
</code>```

but the expiration date is now working like expect.

答:
Ok, there problem seems to be this:

```<code>var _expirationDateUTC = moment.utc(limitDateStr).utcOffset(parseFloat(timezone)).format();
</code>```

where limitDateStr = "2017-07-04T00:00:00.000Z";

What you are doing up to this point is feeding moment with this date and then apply the timezone offset, which will substract the timezone(in this case -6) to the date you are actually feeding.

"2017-07-04T00:00:00.000Z" - 6 hours = "2017-07-03T18:00:00-06:00"

What you are looking for is not to calculate the limitDate in a different timezone but to have limitDate to be the same as the utc but in a different timezone.

So you need this block of code which will add the hours from the target zone:

```<code>var limitDateStr = moment("2017-07-04T00:00:00.000Z");
var timezone = "-6.0"

//Substract the timezone offset to the time;
//This should be: "2017-07-04T06:00:00.000Z"
limitDateStr.subtract({hours: parseFloat(timezone)});

//Now you can apply the offseting
//and this will become: "2017-07-04T00:00:00-06:00"
var _expirationDateUTC = moment.utc(limitDateStr).utcOffset(parseFloat(timezone)).format();

var today = moment.utc().utcOffset(parseFloat(timezone)).format();

var hasExpired = today.isAfter(_expirationDateUTC);
</code>```

Body:
I stored a string of UTC Date (without time):

var limitDateStr = "2017-07-04T00:00:00.000Z";

And a TIMEZONE in hours (based on this), not in Zone Name (like America/Antigua)

var timezone = "-6.0"; //could be from -12.0 to 12.0

The problem is: Verify if actual date, is greater than limitDate in the same Timezone.

What I Do with Moment.js

I Used moment for change the timezone, but when y change the offset. The date is changed too:

  var _expirationDateUTC = moment.utc(limitDateStr).utcOffset(parseFloat(timezone)).format();
  // "2017-07-03T18:00:00-06:00"

Instead of 2017-07-04T00:00:00-06:00

Actual date, works great: (except for Days Savings)

var today = moment.utc().utcOffset(parseFloat(timezone)).format();
//"2017-07-04T15:32:49-06:00"

And I want to compare... maybe with moment function:

today.isAfter(_expirationDateUTC);

but the expiration date is now working like expect.

Body:
Ok, there problem seems to be this:

var _expirationDateUTC = moment.utc(limitDateStr).utcOffset(parseFloat(timezone)).format();

where limitDateStr = "2017-07-04T00:00:00.000Z";

What you are doing up to this point is feeding moment with this date and then apply the timezone offset, which will substract the timezone(in this case -6) to the date you are actually feeding.

"2017-07-04T00:00:00.000Z" - 6 hours = "2017-07-03T18:00:00-06:00"

What you are looking for is not to calculate the limitDate in a different timezone but to have limitDate to be the same as the utc but in a different timezone.

So you need this block of code which will add the hours from the target zone:

var limitDateStr = moment("2017-07-04T00:00:00.000Z");
var timezone = "-6.0"

//Substract the timezone offset to the time;
//This should be: "2017-07-04T06:00:00.000Z"
limitDateStr.subtract({hours: parseFloat(timezone)});

//Now you can apply the offseting
//and this will become: "2017-07-04T00:00:00-06:00"
var _expirationDateUTC = moment.utc(limitDateStr).utcOffset(parseFloat(timezone)).format();

var today = moment.utc().utcOffset(parseFloat(timezone)).format();

var hasExpired = today.isAfter(_expirationDateUTC);


问:
sticky navigation jumps with css and jquery
I am trying to build sticky navigation but the problem is that when the scrollTop reaches 300px my navigation is jumping too fast and I want to scroll it smoothly and I am not sure where the problem is ( why the navigation is jumping out(bouncing) ).

https://jsfiddle.net/7mgLkk53/1/

```<code>jsfiddle
</code>```

答:
change your scrollTop pixel logic if its more that 0 then add "main-head-scrolled" class

```<code>$(this).scrollTop() > 0
</code>```

here is a working fiddle

https://jsfiddle.net/7mgLkk53/3/

Body:
I am trying to build sticky navigation but the problem is that when the scrollTop reaches 300px my navigation is jumping too fast and I want to scroll it smoothly and I am not sure where the problem is ( why the navigation is jumping out(bouncing) ).

https://jsfiddle.net/7mgLkk53/1/

jsfiddle

Body:
change your scrollTop pixel logic if its more that 0 then add "main-head-scrolled" class

$(this).scrollTop() > 0

here is a working fiddle

https://jsfiddle.net/7mgLkk53/3/


问:
Firebase Storage keeps replacing image when uploading
I am trying to upload 2 images at once and get the DownloadURL to go to the Firebase Database but the second Image function keeps replacing the first one so when I click on the downloadURL for either the first or second it will only grab the second Image. This is my code.</p>

```<code>@IBAction func upload(_ sender: Any) {

    let storageRef = Storage.storage().reference().child("images/\(NSUUID().uuidString)/image.png")
    if let uploadData = UIImagePNGRepresentation(self.myImageView1.image!){
    storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in

        let storageRef2 = Storage.storage().reference().child("images2/\(NSUUID().uuidString)/image2.png")
        if let uploadData2 = UIImagePNGRepresentation(self.myImageView2.image!){
        storageRef2.putData(uploadData2, metadata: nil, completion: { (metadata, error) in

                if error != nil {
                        print("error")
                        return

                    } else {
                        let downloadURL = metadata?.downloadURL()?.absoluteString
                        let downloadURL2 = metadata?.downloadURL()?.absoluteString

                        self.ref?.child("Posts").childByAutoId().setValue(["Title": self.titleText.text, "Subtitle": self.subtitleText.text, "Article": self.articleText.text, "Author": self.authorText.text, "Date": self.dateText.text, "Tags": self.tagsText.text, "PostType": self.postType.text, "PostStyle": self.postStyle.text, "PostSize": self.postSize.text, "Download URL": (downloadURL), "Download URL 2": (downloadURL2)])

            }
</code>```

答:
Ofcourse your link is the same, your downloadURL and downloadURL2 is referring to the same metadata?.downloadURL?.absoluteString. Try this:</p>

```<code>@IBAction func upload(_ sender: Any) {
checkExist(url: inserttheurlhere){ succes in
if succes{
//image exist
//continue your work here when the picture exist
}else{
//error downloading, not exist or other failure
//continue your work here when no exist
}

    let storageRef = Storage.storage().reference().child("images/\(NSUUID().uuidString)/image.png")
    if let uploadData = UIImagePNGRepresentation(self.myImageView1.image!){
    storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in

        let storageRef2 = Storage.storage().reference().child("images2/\(NSUUID().uuidString)/image2.png")
        if let uploadData2 = UIImagePNGRepresentation(self.myImageView2.image!){
        storageRef2.putData(uploadData2, metadata: nil, completion: { (metadataSecond, error) in

                if error != nil {
                        print("error")
                        return

                    } else {
                        let downloadURL = metadata?.downloadURL()?.absoluteString
                        let downloadURL2 = metadataSecond?.downloadURL()?.absoluteString

                        self.ref?.child("Posts").childByAutoId().setValue(["Title": self.titleText.text, "Subtitle": self.subtitleText.text, "Article": self.articleText.text, "Author": self.authorText.text, "Date": self.dateText.text, "Tags": self.tagsText.text, "PostType": self.postType.text, "PostStyle": self.postStyle.text, "PostSize": self.postSize.text, "Download URL": (downloadURL), "Download URL 2": (downloadURL2)])

            }

func checkExist(url: String, completionHandler:@escaping (Bool) -> ()){
let storageRef = Storage.storage().reference().child(url)
        if let uploadData = UIImagePNGRepresentation(self.theuiview.image!){
        storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
if error == nil && metadata != nil{
completionHandler(true)
}else{
completionHandler(false)
}
})
}
</code>```

Body:
I am trying to upload 2 images at once and get the DownloadURL to go to the Firebase Database but the second Image function keeps replacing the first one so when I click on the downloadURL for either the first or second it will only grab the second Image. This is my code.

@IBAction func upload(_ sender: Any) {

    let storageRef = Storage.storage().reference().child("images/\(NSUUID().uuidString)/image.png")
    if let uploadData = UIImagePNGRepresentation(self.myImageView1.image!){
    storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in

        let storageRef2 = Storage.storage().reference().child("images2/\(NSUUID().uuidString)/image2.png")
        if let uploadData2 = UIImagePNGRepresentation(self.myImageView2.image!){
        storageRef2.putData(uploadData2, metadata: nil, completion: { (metadata, error) in

                if error != nil {
                        print("error")
                        return

                    } else {
                        let downloadURL = metadata?.downloadURL()?.absoluteString
                        let downloadURL2 = metadata?.downloadURL()?.absoluteString

                        self.ref?.child("Posts").childByAutoId().setValue(["Title": self.titleText.text, "Subtitle": self.subtitleText.text, "Article": self.articleText.text, "Author": self.authorText.text, "Date": self.dateText.text, "Tags": self.tagsText.text, "PostType": self.postType.text, "PostStyle": self.postStyle.text, "PostSize": self.postSize.text, "Download URL": (downloadURL), "Download URL 2": (downloadURL2)])

            }

Body:
Ofcourse your link is the same, your downloadURL and downloadURL2 is referring to the same metadata?.downloadURL?.absoluteString. Try this:

@IBAction func upload(_ sender: Any) {
checkExist(url: inserttheurlhere){ succes in
if succes{
//image exist
//continue your work here when the picture exist
}else{
//error downloading, not exist or other failure
//continue your work here when no exist
}

    let storageRef = Storage.storage().reference().child("images/\(NSUUID().uuidString)/image.png")
    if let uploadData = UIImagePNGRepresentation(self.myImageView1.image!){
    storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in

        let storageRef2 = Storage.storage().reference().child("images2/\(NSUUID().uuidString)/image2.png")
        if let uploadData2 = UIImagePNGRepresentation(self.myImageView2.image!){
        storageRef2.putData(uploadData2, metadata: nil, completion: { (metadataSecond, error) in

                if error != nil {
                        print("error")
                        return

                    } else {
                        let downloadURL = metadata?.downloadURL()?.absoluteString
                        let downloadURL2 = metadataSecond?.downloadURL()?.absoluteString

                        self.ref?.child("Posts").childByAutoId().setValue(["Title": self.titleText.text, "Subtitle": self.subtitleText.text, "Article": self.articleText.text, "Author": self.authorText.text, "Date": self.dateText.text, "Tags": self.tagsText.text, "PostType": self.postType.text, "PostStyle": self.postStyle.text, "PostSize": self.postSize.text, "Download URL": (downloadURL), "Download URL 2": (downloadURL2)])

            }

func checkExist(url: String, completionHandler:@escaping (Bool) -> ()){
let storageRef = Storage.storage().reference().child(url)
        if let uploadData = UIImagePNGRepresentation(self.theuiview.image!){
        storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
if error == nil && metadata != nil{
completionHandler(true)
}else{
completionHandler(false)
}
})
}


问:
Shiny App - passing the string to variable
I am trying to build Shiny App that does sentiment analysis. I have the code that works fine when i execute the script normally where Rstudio is importing the data from email.csv file. This file contains only 2 columns ( SentTo and RawText) and the text i am analyzing is located in B2 cell.
Once i run the code below i get nice chart that measure the sentiment.

```<code>library(readr)
library("ggplot2")
library('syuzhet')
Emails <- read_csv("C:/email.csv")
d<-get_nrc_sentiment(Emails$RawText)
td<-data.frame(t(d))
td_new <- data.frame(rowSums(td[1:14]))
names(td_new)[1] <- "count"
td_new <- cbind("sentiment" = rownames(td_new), td_new)
rownames(td_new) <- NULL
td_new2<-td_new[1:8,]
qplot(sentiment, data=td_new2, weight=count,
geom="bar",fill=sentiment)+ggtitle("Email sentiments")
</code>```

Now what i am trying to do is to modify this code a bit and build the Shiny application by doing next:

ui.R

```<code># Adding the Imput text field to the app
shinyUI(fluidPage(

textAreaInput("UserInput", "Caption", "Please Enter Your Text", width =
"500px", height = "300px"),

mainPanel(
plotOutput("distPlot"))
))
</code>```

Server.R

```<code>library(shiny)
library(syuzhet)
library(ggplot2)

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

output$distPlot <- renderPlot({

Emails <- input$UserInput

d<-get_nrc_sentiment(Emails)
td<-data.frame(t(d))
td_new <- data.frame(rowSums(td[1:14]))
names(td_new)[1] <- "count"
td_new <- cbind("sentiment" = rownames(td_new), td_new)
rownames(td_new) <- NULL
td_new2<-td_new[1:8,]
qplot(sentiment, data=td_new2, weight=count,
geom="bar",fill=sentiment)+ggtitle("Email sentiments")

  })
})
</code>```

After i run the app i get this error:

So ti builds the app but even when i paste some text in to the field it seems that the code i am using in server.R part is not doing what it needs to do.
If i replace the line in server.R part (Emails <- input$UserInput) with (Emails <- read_csv("C:/email.csv"))
than it works fine. This tells me that the issue is within the way i am passing the text to the Emails. Through the input form its text through the csv file it is a second row and second column that contains the data. The code that follows i think its looking that specific format.
Anybody has suggestion on how to modify this to make it work?
Thank you in advance.

答:
Before plotting in shiny, first have it output the user input so that you understand what is being passed to the next step. verbatimTextOutput('input$UserInput') and verbatimTextOutput('dput(input$UserInput)'). I'm guessing this will be a character vector of length 1.

Now, go back to your code outside of shiny and pass it this same input, formatted exactly the same. Right now your code that works is getting a data.frame from a csv file and passed a column, which would be a character vector.

Once you get it working outside of shiny, using the input as parsed by shiny, the fixes to make your shiny app work should be clear.

Body:
I am trying to build Shiny App that does sentiment analysis. I have the code that works fine when i execute the script normally where Rstudio is importing the data from email.csv file. This file contains only 2 columns ( SentTo and RawText) and the text i am analyzing is located in B2 cell.
Once i run the code below i get nice chart that measure the sentiment.

library(readr)
library("ggplot2")
library('syuzhet')
Emails <- read_csv("C:/email.csv")
d<-get_nrc_sentiment(Emails$RawText)
td<-data.frame(t(d))
td_new <- data.frame(rowSums(td[1:14]))
names(td_new)[1] <- "count"
td_new <- cbind("sentiment" = rownames(td_new), td_new)
rownames(td_new) <- NULL
td_new2<-td_new[1:8,]
qplot(sentiment, data=td_new2, weight=count,
geom="bar",fill=sentiment)+ggtitle("Email sentiments")

Now what i am trying to do is to modify this code a bit and build the Shiny application by doing next:

ui.R

# Adding the Imput text field to the app
shinyUI(fluidPage(

textAreaInput("UserInput", "Caption", "Please Enter Your Text", width =
"500px", height = "300px"),

mainPanel(
plotOutput("distPlot"))
))

Server.R

library(shiny)
library(syuzhet)
library(ggplot2)

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

output$distPlot <- renderPlot({

Emails <- input$UserInput

d<-get_nrc_sentiment(Emails)
td<-data.frame(t(d))
td_new <- data.frame(rowSums(td[1:14]))
names(td_new)[1] <- "count"
td_new <- cbind("sentiment" = rownames(td_new), td_new)
rownames(td_new) <- NULL
td_new2<-td_new[1:8,]
qplot(sentiment, data=td_new2, weight=count,
geom="bar",fill=sentiment)+ggtitle("Email sentiments")

  })
})

After i run the app i get this error:

So ti builds the app but even when i paste some text in to the field it seems that the code i am using in server.R part is not doing what it needs to do.
If i replace the line in server.R part (Emails <- input$UserInput) with (Emails <- read_csv("C:/email.csv"))
than it works fine. This tells me that the issue is within the way i am passing the text to the Emails. Through the input form its text through the csv file it is a second row and second column that contains the data. The code that follows i think its looking that specific format.
Anybody has suggestion on how to modify this to make it work?
Thank you in advance.