来源: stackexchange

问:
I want to check if parameter exist as an id in the body. how can I do that without hardcoding and using jquery? Javascript

```<code><a id="Param">This is an html element</a>

<script>

function Append(param1,text)
{
    if(document.getElementById(param1))
    {

        return document.getElementById(param1)+text;
    }
    else
    {
        console.error("the element was not found");
    }
}

var app1=Append("Anything",". yes"); //i called the append twice first is to see the output when false
var app2=Append("Param",". hi")//second is to see the output when true. I want the output to be "This is an html element. hi"
</code>```

this is the code that I have. I wanted to have a function that uses two parameters. The first one is to for an html element id and the second one is for the text that will be appended to the first parameter. How can the function check if "Param" is an id without hard coding or using jquery?

答:
A string-query might be your best bet by making the PARAM dynamic and you can change it based on what the url passes to the script. index.php?param1=myvalue

Here is a reference article I used last time I had to do it myself: https://www.joezimjs.com/javascript/3-ways-to-parse-a-query-string-in-a-url/

Respectfully,
SFR

ContentLicense: CC BY-SA 3.0

Body: This is an html element


问:
Hiding elements via JavaScript/CSS
Some interesting JavaScript I hadn't seen before:

```<code>  var html = $( 'html' );
  if( html.className !== '' )
    html.className = '';
</code>```

I’m not sure how it works, but it seems like that assignment has the effect of changing the CSS display value of every element on the page which has the className selector from block to none.

Is anybody familiar with this behavior? Am I seeing it right?

EDIT:
OK, in response to those who say it's not valid jQuery, you're right. It's a shorthand way of describing the HTML element that was passed in by another function. And I didn't write it, just trying to understand it. It works, I want to know why.

答:
This is actually a jQuery to select the html node and change the value of css class to it.

lets says you want to change the padding of the html document using a click event.

your onclick event would call that function to assign the css class with the desired padding.

Title: Hiding elements via JavaScript/CSS

Body:
Some interesting JavaScript I hadn't seen before:

  var html = $( 'html' );
  if( html.className !== '' )
    html.className = '';

I’m not sure how it works, but it seems like that assignment has the effect of changing the CSS display value of every element on the page which has the className selector from block to none.

Is anybody familiar with this behavior? Am I seeing it right?

EDIT:
OK, in response to those who say it's not valid jQuery, you're right. It's a shorthand way of describing the HTML element that was passed in by another function. And I didn't write it, just trying to understand it. It works, I want to know why.


问:
If statement for drop down list
So I have two drop down lists in my code where the data is retrieved from a SQL table.

I can't figure out an IF statement to show an error message if both of these two drop down lists have not been selected. I have added a list item in to tell the user to select a date/time.

I tried an if statement but this would not work.

If Statement:

```<code>    If DropDownList2.SelectedValue And DropDownList3.SelectedValue = Nothing Then

        warninginfo.Visible = True
    Else
        Response.Redirect("ConfirmationBooking.aspx")

    End If
</code>```

Code:

```<code>    <asp:DropDownList ID="DropDownList3" runat="server" DataSourceID="SqlDataSource2" DataTextField="Time" DataValueField="Time"  AppendDataBoundItems="True" width="162px" Height="31px">
    <asp:ListItem>-- Please Select a Time --</asp:ListItem>
    </asp:DropDownList>

    <asp:DropDownList ID="DropDownList2" runat="server" CssClass="auto-style2" DataSourceID="SqlDataSource1" DataTextField="Date" DataValueField="Date" AppendDataBoundItems="True" Width="162px" Height="30px">
    <asp:ListItem>-- Please Select a Date --</asp:ListItem>
    </asp:DropDownList>
</code>```

答:
Your if statement is wrong.  It should be (changed the AND to Or)

```<code>If DropDownList2.SelectedValue Is Nothing Or DropDownList3.SelectedValue Is Nothing Then
</code>```

Another option is to make those two fields required using a RequiredFieldValidator.

```<code><asp:RequiredFieldValidator id="reqFavoriteColor" Text="(Required)"
     InitialValue="none" ControlToValidate="DropDownList2" Runat="server"
 />
</code>```

Title: If statement for drop down list

Body:
So I have two drop down lists in my code where the data is retrieved from a SQL table.

I can't figure out an IF statement to show an error message if both of these two drop down lists have not been selected. I have added a list item in to tell the user to select a date/time.

I tried an if statement but this would not work.

If Statement:

    If DropDownList2.SelectedValue And DropDownList3.SelectedValue = Nothing Then

        warninginfo.Visible = True
    Else
        Response.Redirect("ConfirmationBooking.aspx")

    End If

Code:

    <asp:DropDownList ID="DropDownList3" runat="server" DataSourceID="SqlDataSource2" DataTextField="Time" DataValueField="Time"  AppendDataBoundItems="True" width="162px" Height="31px">
    <asp:ListItem>-- Please Select a Time --</asp:ListItem>
    </asp:DropDownList>

    <asp:DropDownList ID="DropDownList2" runat="server" CssClass="auto-style2" DataSourceID="SqlDataSource1" DataTextField="Date" DataValueField="Date" AppendDataBoundItems="True" Width="162px" Height="30px">
    <asp:ListItem>-- Please Select a Date --</asp:ListItem>
    </asp:DropDownList>

Body:
Your if statement is wrong.  It should be (changed the AND to Or)

If DropDownList2.SelectedValue Is Nothing Or DropDownList3.SelectedValue Is Nothing Then

Another option is to make those two fields required using a RequiredFieldValidator.

<asp:RequiredFieldValidator id="reqFavoriteColor" Text="(Required)"
     InitialValue="none" ControlToValidate="DropDownList2" Runat="server"
 />


问:
Setting a variable in AppleScript based on a list in a Numbers sheet
AppleScript beginner here. Searching high and low hasn't led me to the answer yet.

I'm using AppleScript to help run youth wrestling tournaments. Each division (based on age) is broken down into weight classes. For example: Novice 80 or Cadet 105.

Once a certain group of kids is put into a certain division/weight class, those kids get added to a new sheet that contains their bracket (think March Madness bracket but a small number of kids wrestling instead of playing basketball).

I've figured out how to get a group into a new sheet where they populate the bracket, but when this new sheet is created, I don't know how to make AppleScript change the name of the sheet to the correct division/weight class. I'm sure it has something to do with creating variables based on a list of the divisions/weight classes (that I have), but I can't figure out how to do it. Here's the relevant portion of the code:

```<code>tell document 1
        set active sheet to the last sheet
        set thisSheet to make new sheet
        set the name of thisSheet to "[Division variable – Weight class variable]"
        tell thisSheet
            delete every table
        end tell
</code>```

Any ideas on how to make AppleScript name the sheet like I want?

答:
Try

```<code>set thisSheet to make new sheet with properties  {name:"yourname"}
</code>```

Edit
Some explanation: if your struggling on how to adress third party apps try to load it's library and look up the methods you need. In applescript editor you will find it in the (I guess) menu. Then select the desired app to get the library

Body:
AppleScript beginner here. Searching high and low hasn't led me to the answer yet.

I'm using AppleScript to help run youth wrestling tournaments. Each division (based on age) is broken down into weight classes. For example: Novice 80 or Cadet 105.

Once a certain group of kids is put into a certain division/weight class, those kids get added to a new sheet that contains their bracket (think March Madness bracket but a small number of kids wrestling instead of playing basketball).

I've figured out how to get a group into a new sheet where they populate the bracket, but when this new sheet is created, I don't know how to make AppleScript change the name of the sheet to the correct division/weight class. I'm sure it has something to do with creating variables based on a list of the divisions/weight classes (that I have), but I can't figure out how to do it. Here's the relevant portion of the code:

tell document 1
        set active sheet to the last sheet
        set thisSheet to make new sheet
        set the name of thisSheet to "[Division variable – Weight class variable]"
        tell thisSheet
            delete every table
        end tell

Any ideas on how to make AppleScript name the sheet like I want?

Body:
Try

set thisSheet to make new sheet with properties  {name:"yourname"}

Edit
Some explanation: if your struggling on how to adress third party apps try to load it's library and look up the methods you need. In applescript editor you will find it in the (I guess) menu. Then select the desired app to get the library


问:
trying to upload an image into canvas using button. But i get errors
Exception in Tkinter callback:

Traceback (most recent call last):

  File "C:\Users\ANANTI\Anaconda2\lib\lib-tk\Tkinter.py", line 1542, in call
     return self.func(*args)

  File "C:/Users/ANANTI/Desktop/dataset/untitled8.py", line 50, in showImg
      label = Label(master, image=photo)

  NameError: global name 'master' is not defined

答: The error message tells you exactly why the code isn't working. You have not defined master. You should put the name of the widget that you would like the Label to go (your canvas?) where master is.


问:
Azure service bus or just Azure web app when using SignalR
I never used the Azure. Now, i with a problem.
I am going to do a Chat on Xamarin Forms using SignalR. So, the chat will have a 1:1 and a group 1:all . Its for a small group of 700 to 1.000 persons. Looking at the internet, i didnt understand if i have to pay for Azure App Service (standard) + Azure Bus Service, or just Azure Bus Service, or just Azure App Service. </p>

答:
Short answer: you only need to pay for Azure App Service to create a single Web App if you want to use SignalR. </p>

<p>The only reason you'll need Service Bus is if you decide to scale your Web App to multiple instances. To synchronize across multiple web apps, SignalR requires a messaging backplane. That's what Service Bus would be used for. Your other options for a SignalR messaging backplane are Redis (very fast), or Azure SQL (slower). I personally use Service Bus for my SignalR messaging backplane. But again, you do NOT need Service Bus if you're only using one instance for your web app.  </p>

Body:
Short answer: you only need to pay for Azure App Service to create a single Web App if you want to use SignalR.

The only reason you'll need Service Bus is if you decide to scale your Web App to multiple instances. To synchronize across multiple web apps, SignalR requires a messaging backplane. That's what Service Bus would be used for. Your other options for a SignalR messaging backplane are Redis (very fast), or Azure SQL (slower). I personally use Service Bus for my SignalR messaging backplane. But again, you do NOT need Service Bus if you're only using one instance for your web app.


问:
Mockito unit test BaseObserver and static method with context
I am facing with Unit testing for the first time and I would like to know what is the best approach for the following scenario.
I am using Mockito for the tests. The following test is for logic(Presenter) layer and I am trying to verify certain behaviors of the view.

App classes

The method of the Presenter that need to be include in the test:

```<code>public void loadWeather() {

CityDetailsModel selectedCity = getDbHelper().getSelectedCityModel();

if (selectedCity != null) {
  getCompositeDisposableHelper().execute(
      getApiHelper().weatherApiRequest(selectedCity.getLatitude(), selectedCity.getLongitude()),
      new WeatherObserver(getMvpView()));
} else {
  getMvpView().showEmptyView();
}
</code>```

}

WeatherObserver:

```<code> public class WeatherObserver extends BaseViewSubscriber<DayMvpView, WeatherResponseModel> {

   public WeatherObserver(DayMvpView view) {
      super(view);
    }

    @Override public void onNext(WeatherResponseModel weatherResponseModel) {
      super.onNext(weatherResponseModel);

      if (weatherResponseModel.getData().isEmpty()) {
        getMvpView().showEmptyView();
      } else {
        getMvpView().showWeather(weatherResponseModel.getData());
      }
    }
  }
</code>```

BaseViewSubscriber (Default DisposableObserver base class to be used whenever we want default error handling):

```<code> public class BaseViewSubscriber<V extends BaseMvpView, T> extends DisposableObserver<T> {

  private ErrorHandlerHelper errorHandlerHelper;
  private V view;

  public BaseViewSubscriber(V view) {
    this.view = view;
    errorHandlerHelper = WeatherApplication.getApplicationComponent().errorHelper();
  }

  public V getView() {
    return view;
  }

  public boolean shouldShowError() {
    return true;
  }

  protected boolean shouldShowLoading() {
    return true;
  }

  @Override public void onStart() {
    if (!AppUtils.isNetworkAvailable(WeatherApplication.getApplicationComponent().context())) {
      onError(new InternetConnectionException());
      return;
    }

    if (shouldShowLoading()) {
      view.showLoading();
    }
    super.onStart();
  }

  @Override public void onError(Throwable e) {
    if (view == null) {
      return;
    }

    if (shouldShowLoading()) {
      view.hideLoading();
    }

    if (shouldShowError()) {
      view.onError(errorHandlerHelper.getProperErrorMessage(e));
    }
  }

  @Override public void onComplete() {
    if (view == null) {
      return;
    }

    if (shouldShowLoading()) {
      view.hideLoading();
    }
  }

  @Override public void onNext(T t) {
    if (view == null) {
      return;
    }
  }
}
</code>```

CompositeDisposableHelper (CompositeDisposable helper class):

```<code>public class CompositeDisposableHelper {

  public CompositeDisposable disposables;
  public TestScheduler testScheduler;

  @Inject public CompositeDisposableHelper(CompositeDisposable disposables) {
    this.disposables = disposables;
    testScheduler = new TestScheduler();
  }

  public <T> void execute(Observable<T> observable, DisposableObserver<T> observer) {
    addDisposable(observable.subscribeOn(testScheduler)
        .observeOn(testScheduler)
        .subscribeWith(observer));
  }

  public void dispose() {
    if (!disposables.isDisposed()) {
      disposables.dispose();
    }
  }

  public TestScheduler getTestScheduler() {
    return testScheduler;
  }

  public void addDisposable(Disposable disposable) {
    disposables.add(disposable);
  }
}
</code>```

My test:

```<code>  @Test public void loadSuccessfully() {
    WeatherResponseModel responseModel = new WeatherResponseModel();
    List<WeatherModel> list = new ArrayList<>();
    list.add(new WeatherModel());
    responseModel.setData(list);

    CityDetailsModel cityDetailsModel = new CityDetailsModel();
    cityDetailsModel.setLongitude("");
    cityDetailsModel.setLatitude("");

    when(dbHelper.getSelectedCityModel()).thenReturn(cityDetailsModel);

    when(apiHelper.weatherApiRequest(anyString(), anyString())).thenReturn(
        Observable.just(responseModel));

    dayPresenter.loadWeather();

    compositeDisposableHelper.getTestScheduler().triggerActions();

    verify(dayMvpView).showWeather(list);
    verify(dayMvpView, never()).showEmptyView();
    verify(dayMvpView, never()).onError(anyString());
  }
</code>```

When I try to run the test, I get NullPointer, because new WeatherObserver(getMvpView()) is called, and in the BaseViewSubscriber errorHandlerHelper is null because getApplicationCopomnent is null.
As well NullPointer is thrown in the static method AppUtils.isNetworkAvailable() for the same reason.

When I try to comment these lines, the test is OK.

My questions are:

Should I use Dagger for the Unit test as well or? If yes please give
me example for my test.

Should I use PowerMockito for the static    method
AppUtils.isNetworkAvailable()? If yes, is it ok just because    of
this method to use PowerMockito Runner

@RunWith(PowerMockRunner.class)?

答:
Should I use Dagger for the Unit test as well or? If yes please give me example for my test.

You don't have to use Dagger necessarily at the test, but that's where Dependency Injection will benefit you, as it will help you strip your dependencies out, and tests will be able to replace them.

Should I use PowerMockito for the static method AppUtils.isNetworkAvailable()? If yes, is it ok just because of this method to use PowerMockito Runner
  @RunWith(PowerMockRunner.class)?

Static methods are generally bad for testing, as you cannot replace them (at least not easily and without PowerMock) for testing purposes.

The better practice is to use Dagger for the production code to inject those dependencies, preferably at Constructor, so at tests you can simply provide those dependencies according to test needs (using mocks or fakes where necessary).

In your case, you can add both ErrorHandlerHelper and AppUtils to BaseViewSubscriber Constructor. as BaseViewSubscriber shouldn't be injected, you will need to provide those modules to it from outside, in the presenter, that where you should use Injection to get those Objects. again at the Constructor.

At test, simply replace or provide this objects to the presenter that in it's turn will hand it over to the BaseViewSubscriber.

You can read more about tests seams at android here.

Besides that, it some very odd to me the OO hierarchy of Observer and Disposable that wraps the Observable for getting common behavior, it's essentially breaking the functional stream oriented reactive approach, you might want to consider using patterns like compose using Transformers and using doOnXXX operators do apply common behavior at reactive streams.

Body:
I am facing with Unit testing for the first time and I would like to know what is the best approach for the following scenario.
I am using Mockito for the tests. The following test is for logic(Presenter) layer and I am trying to verify certain behaviors of the view.

App classes

The method of the Presenter that need to be include in the test:

public void loadWeather() {

CityDetailsModel selectedCity = getDbHelper().getSelectedCityModel();

if (selectedCity != null) {
  getCompositeDisposableHelper().execute(
      getApiHelper().weatherApiRequest(selectedCity.getLatitude(), selectedCity.getLongitude()),
      new WeatherObserver(getMvpView()));
} else {
  getMvpView().showEmptyView();
}

}

WeatherObserver:

 public class WeatherObserver extends BaseViewSubscriber<DayMvpView, WeatherResponseModel> {

   public WeatherObserver(DayMvpView view) {
      super(view);
    }

    @Override public void onNext(WeatherResponseModel weatherResponseModel) {
      super.onNext(weatherResponseModel);

      if (weatherResponseModel.getData().isEmpty()) {
        getMvpView().showEmptyView();
      } else {
        getMvpView().showWeather(weatherResponseModel.getData());
      }
    }
  }

BaseViewSubscriber (Default DisposableObserver base class to be used whenever we want default error handling):

 public class BaseViewSubscriber<V extends BaseMvpView, T> extends DisposableObserver<T> {

  private ErrorHandlerHelper errorHandlerHelper;
  private V view;

  public BaseViewSubscriber(V view) {
    this.view = view;
    errorHandlerHelper = WeatherApplication.getApplicationComponent().errorHelper();
  }

  public V getView() {
    return view;
  }

  public boolean shouldShowError() {
    return true;
  }

  protected boolean shouldShowLoading() {
    return true;
  }

  @Override public void onStart() {
    if (!AppUtils.isNetworkAvailable(WeatherApplication.getApplicationComponent().context())) {
      onError(new InternetConnectionException());
      return;
    }

    if (shouldShowLoading()) {
      view.showLoading();
    }
    super.onStart();
  }

  @Override public void onError(Throwable e) {
    if (view == null) {
      return;
    }

    if (shouldShowLoading()) {
      view.hideLoading();
    }

    if (shouldShowError()) {
      view.onError(errorHandlerHelper.getProperErrorMessage(e));
    }
  }

  @Override public void onComplete() {
    if (view == null) {
      return;
    }

    if (shouldShowLoading()) {
      view.hideLoading();
    }
  }

  @Override public void onNext(T t) {
    if (view == null) {
      return;
    }
  }
}

CompositeDisposableHelper (CompositeDisposable helper class):

public class CompositeDisposableHelper {

  public CompositeDisposable disposables;
  public TestScheduler testScheduler;

  @Inject public CompositeDisposableHelper(CompositeDisposable disposables) {
    this.disposables = disposables;
    testScheduler = new TestScheduler();
  }

  public <T> void execute(Observable<T> observable, DisposableObserver<T> observer) {
    addDisposable(observable.subscribeOn(testScheduler)
        .observeOn(testScheduler)
        .subscribeWith(observer));
  }

  public void dispose() {
    if (!disposables.isDisposed()) {
      disposables.dispose();
    }
  }

  public TestScheduler getTestScheduler() {
    return testScheduler;
  }

  public void addDisposable(Disposable disposable) {
    disposables.add(disposable);
  }
}

My test:

  @Test public void loadSuccessfully() {
    WeatherResponseModel responseModel = new WeatherResponseModel();
    List<WeatherModel> list = new ArrayList<>();
    list.add(new WeatherModel());
    responseModel.setData(list);

    CityDetailsModel cityDetailsModel = new CityDetailsModel();
    cityDetailsModel.setLongitude("");
    cityDetailsModel.setLatitude("");

    when(dbHelper.getSelectedCityModel()).thenReturn(cityDetailsModel);

    when(apiHelper.weatherApiRequest(anyString(), anyString())).thenReturn(
        Observable.just(responseModel));

    dayPresenter.loadWeather();

    compositeDisposableHelper.getTestScheduler().triggerActions();

    verify(dayMvpView).showWeather(list);
    verify(dayMvpView, never()).showEmptyView();
    verify(dayMvpView, never()).onError(anyString());
  }

When I try to run the test, I get NullPointer, because new WeatherObserver(getMvpView()) is called, and in the BaseViewSubscriber errorHandlerHelper is null because getApplicationCopomnent is null.
As well NullPointer is thrown in the static method AppUtils.isNetworkAvailable() for the same reason.

When I try to comment these lines, the test is OK.

My questions are:

Should I use Dagger for the Unit test as well or? If yes please give
me example for my test.

Should I use PowerMockito for the static    method
AppUtils.isNetworkAvailable()? If yes, is it ok just because    of
this method to use PowerMockito Runner

@RunWith(PowerMockRunner.class)?


问:
How do I query for documents that contain a specific key/value pair
Using monogo's shell,
    db.collection.find( {key:value} )
returns exactly what I want, only I want to make this query from a browser using a URL like localhost:8000/api/profiles?key=value

I'm trying to use Express, Node and Mongoose.

Here is the code I have:

```<code>//Get By query route
router.get('/:param', function(req, res){
    var param = req.query(param);
    getProfilebyQuery(function(err, profiles) {
    if(err){
        throw err;
    }
res.json(profiles)
    })
});
//METHODS GO HERE
//These methods are stored as variables and called in the Routes above.
//Get by Query
var getProfilebyQuery = function(param, callback) {
    Iprofile.find(param, callback);
};
</code>```

What you can't see is "Iprofile" requires my mongoose schemas. I can't tell what I'm doing wrong.

答:
Since you're using query parameters (difference between req.query and req.params ), you don't need to define /:param. You need to use req.query.

Also you are not passing the param variable to function.

```<code>//Get By query route
router.get('/', function(req, res){
  var param = req.query;
  getProfilebyQuery(param, function(err, profiles) { //pass param
    if(err){
      throw err;
    }
    res.json(profiles)
  })
});
//METHODS GO HERE
//These methods are stored as variables and called in the Routes above.
//Get by Query
var getProfilebyQuery = function(param, callback) {
  Iprofile.find(param, callback);
};
</code>```

Body:
Using monogo's shell,
    db.collection.find( {key:value} )
returns exactly what I want, only I want to make this query from a browser using a URL like localhost:8000/api/profiles?key=value

I'm trying to use Express, Node and Mongoose.

Here is the code I have:

//Get By query route
router.get('/:param', function(req, res){
    var param = req.query(param);
    getProfilebyQuery(function(err, profiles) {
    if(err){
        throw err;
    }
res.json(profiles)
    })
});
//METHODS GO HERE
//These methods are stored as variables and called in the Routes above.
//Get by Query
var getProfilebyQuery = function(param, callback) {
    Iprofile.find(param, callback);
};

What you can't see is "Iprofile" requires my mongoose schemas. I can't tell what I'm doing wrong.

Body:
Since you're using query parameters (difference between req.query and req.params ), you don't need to define /:param. You need to use req.query.

Also you are not passing the param variable to function.

//Get By query route
router.get('/', function(req, res){
  var param = req.query;
  getProfilebyQuery(param, function(err, profiles) { //pass param
    if(err){
      throw err;
    }
    res.json(profiles)
  })
});
//METHODS GO HERE
//These methods are stored as variables and called in the Routes above.
//Get by Query
var getProfilebyQuery = function(param, callback) {
  Iprofile.find(param, callback);
};


问:
No 'items' candidates produce the expected contextual result type '(Observable<[Product]>) -> (_) -> _'
Here is my code snippet:

```<code>class ProductCategoryCell: UITableViewCell {

  @IBOutlet weak var collectionViewProducts: UICollectionView!

  // other stuff...

  func setProducts() {
    let productsObservable = Observable.just([
      Product(name: "test", price: 10.0),
      Product(name: "test", price: 10.0),
      Product(name: "test", price: 10.0)
    ])

    productsObservable.bindTo(collectionViewProducts.rx.items(cellIdentifier: "ProductCell", cellType: ProductCell.self)) {
      (row, element, cell) in
      cell.setProduct(element)
    }.disposed(by: disposeBag)
  }
}
</code>```

It is giving me a build error:

No 'items' candidates produce the expected contextual result type '(Observable<[Product]>) -> (_) -> _'

In my view controller, I am populating table view with a similar code:

```<code>let productsObservable = Observable.just(testProducts)
productsObservable.bindTo(tableViewProducts.rx.items(cellIdentifier: "ProductCategoryCell", cellType: ProductCategoryCell.self)) { (row, element, cell) in
        cell.setCategory(category: element)
}.disposed(by: disposeBag)
</code>```

This code works normally for. What am I doing wrong?

答:
I was able to reproduce the error message you are getting. You did not post the code for your ProductCell's setProduct() method but I guess you might have the same problem that I had.

This is my dummy ProductCell implementation:

```<code>class ProductCell: UICollectionViewCell {
    func setProduct(product: Product) {
        // do stuff
    }
}
</code>```

Now when I use the code in your answer:

```<code>productsObservable.bindTo(collectionViewProducts.rx.items(cellIdentifier: "ProductCell", cellType: ProductCell.self)) { (row, element, cell) in
   cell.setProduct(element)
}
.disposed(by: disposeBag)
</code>```

I get the same error than you:

No 'items' candidates produce the expected contextual result type
  '(Observable<[Product]>) -> (_) -> _'

In my case the problem was that I forgot the argument label product when calling setProduct:

After adding the argument label the code compiles without error:

```<code>productsObservable.bindTo(collectionViewProducts.rx.items(cellIdentifier: "ProductCell", cellType: ProductCell.self)) { (row, element, cell) in
   cell.setProduct(product: element)
}
.disposed(by: disposeBag)
</code>```

The compiler's error message is very misleading in this case. When you would try to call setProduct(element) outside of the closure you would get the correct error message:

Missing argument label 'product:' in call

But somehow the compiler does not realize what exactly the problem is when he is inside the closure.

As I mentioned before I don't know how you implemented setProduct in your ProductCell, but because you are calling cell.setCategory(category: element) in your UITableView example I assume that your problem is the missing argument label when you call cell.setProduct(element)

Body:
Here is my code snippet:

class ProductCategoryCell: UITableViewCell {

  @IBOutlet weak var collectionViewProducts: UICollectionView!

  // other stuff...

  func setProducts() {
    let productsObservable = Observable.just([
      Product(name: "test", price: 10.0),
      Product(name: "test", price: 10.0),
      Product(name: "test", price: 10.0)
    ])

    productsObservable.bindTo(collectionViewProducts.rx.items(cellIdentifier: "ProductCell", cellType: ProductCell.self)) {
      (row, element, cell) in
      cell.setProduct(element)
    }.disposed(by: disposeBag)
  }
}

It is giving me a build error:

No 'items' candidates produce the expected contextual result type '(Observable<[Product]>) -> (_) -> _'

In my view controller, I am populating table view with a similar code:

let productsObservable = Observable.just(testProducts)
productsObservable.bindTo(tableViewProducts.rx.items(cellIdentifier: "ProductCategoryCell", cellType: ProductCategoryCell.self)) { (row, element, cell) in
        cell.setCategory(category: element)
}.disposed(by: disposeBag)

This code works normally for. What am I doing wrong?

Body:
I was able to reproduce the error message you are getting. You did not post the code for your ProductCell's setProduct() method but I guess you might have the same problem that I had.

This is my dummy ProductCell implementation:

class ProductCell: UICollectionViewCell {
    func setProduct(product: Product) {
        // do stuff
    }
}

Now when I use the code in your answer:

productsObservable.bindTo(collectionViewProducts.rx.items(cellIdentifier: "ProductCell", cellType: ProductCell.self)) { (row, element, cell) in
   cell.setProduct(element)
}
.disposed(by: disposeBag)

I get the same error than you:

No 'items' candidates produce the expected contextual result type
  '(Observable<[Product]>) -> (_) -> _'

In my case the problem was that I forgot the argument label product when calling setProduct:

After adding the argument label the code compiles without error:

productsObservable.bindTo(collectionViewProducts.rx.items(cellIdentifier: "ProductCell", cellType: ProductCell.self)) { (row, element, cell) in
   cell.setProduct(product: element)
}
.disposed(by: disposeBag)

The compiler's error message is very misleading in this case. When you would try to call setProduct(element) outside of the closure you would get the correct error message:

Missing argument label 'product:' in call

But somehow the compiler does not realize what exactly the problem is when he is inside the closure.

As I mentioned before I don't know how you implemented setProduct in your ProductCell, but because you are calling cell.setCategory(category: element) in your UITableView example I assume that your problem is the missing argument label when you call cell.setProduct(element)


问:
How to handle two dashes in ReST
I'm using Sphinx to document a command line utility written in Python.  I want to be able to document a command line option, such as --region like this:

```<code>**--region**  <region_name>
</code>```

in ReST and then use Sphinx to to generate my HTML and man pages for me.

This works great when generating man pages but in the generated HTML, the -- gets turned into - which is incorrect.  I have found that if I change my source ReST document to look like this:

```<code>**---region**  <region_name>
</code>```

The HTML generates correctly but now my man pages have --- instead of --.  Also incorrect.

I've tried escaping the dashes with a backslash character (e.g. \-\-) but that had no effect.

Any help would be much appreciated.

答:
To add two dashes, add the following:

```<code>.. include:: <isotech.txt>

|minus|\ |minus|\ region
</code>```

Note the backward-slash and the space. This avoids having a space between the minus signs and the name of the parameter.

You only need to include isotech.txt once per page.

With this solution, you can keep the extension smartypants and write two dashes in every part of the text you need. Not just in option lists or literals.

Title: How to handle two dashes in ReST

Body:
I'm using Sphinx to document a command line utility written in Python.  I want to be able to document a command line option, such as --region like this:

**--region**  <region_name>

in ReST and then use Sphinx to to generate my HTML and man pages for me.

This works great when generating man pages but in the generated HTML, the -- gets turned into - which is incorrect.  I have found that if I change my source ReST document to look like this:

**---region**  <region_name>

The HTML generates correctly but now my man pages have --- instead of --.  Also incorrect.

I've tried escaping the dashes with a backslash character (e.g. \-\-) but that had no effect.

Any help would be much appreciated.

Body:
To add two dashes, add the following:

.. include:: <isotech.txt>

|minus|\ |minus|\ region

Note the backward-slash and the space. This avoids having a space between the minus signs and the name of the parameter.

You only need to include isotech.txt once per page.

With this solution, you can keep the extension smartypants and write two dashes in every part of the text you need. Not just in option lists or literals.


问:
CSS on device different to browser
i am using Ionic2 and have an app that has messages. the message looks as follows in a browser:

However, running on an Android or iOS device, it looks as follows:

As you can see, the tail on each message is missing.

Question

If anyone can advise how I can get the style to be consistent and display the tail on all devices?

HTML

```<code><ion-content padding class="messages-page-content">
    <ion-list class="message-list">
      <ion-item class="message-item" *ngFor="let item of firelist | async">
        <div [ngClass]="{'message message-me':(item.memberId1 == me.uid)}">
          <div [ngClass]="{'message message-you':(item.memberId1 == you.uid)}">
            <div class="message-content">{{item.message_text}}</div>
            <span class="time-tick">
                        <span class="message-timestamp-date">{{item.timestamp | amDateFormat: 'D MMM YY'}}</span>
            <span class="message-timestamp">{{item.timestamp | amDateFormat: 'h:mm a'}}</span>
            <div *ngIf="item.memberId1 === me.uid && item.readByReceiver === true">
              <span class="checkmark">
                                <div class="checkmark_stem"></div>
                                <div class="checkmark_kick"></div>
                            </span>
            </div>
            </span>
          </div>
        </div>
      </ion-item>
    </ion-list>
</ion-content>
</code>```

CSS

See: background-image: url(/assets/message-me.png); and background-image: url(/assets/message-you.png);

```<code>.title-timestamp {
  font-size: 11px;
  color: gray;
}

.message-item {
  background-color: transparent;
}

.label {
    overflow: visible;
    white-space: normal;
}

.message-send {
  font-size: 3.2em;
}

.input-wrapper {
    overflow: visible;
}

.item-md.item-block .item-inner {
  padding-left: 8px;
}

.messages-page-navbar {
  .chat-picture {
    width: 50px;
    border-radius: 50%;
    float: left;
  }

  .chat-title {
    line-height: 27px;
    display: inline-block;
  }

  .chat-subtitle {
    font-size: 11px;
    padding: 0px;
  }
}

.messages-page-content {
  > scroll-content {
    padding: 0;
  }

  .message-list {
    background-color: #E0DAD6;
    background-repeat: no-repeat;
    background-size: cover;
  }

  .message-wrapper {
    margin-bottom: 9px;

    &::after {
      content: "";
      display: table;
      clear: both;
    }
  }

  .message {
    display: inline-block;
    position: relative;
    max-width: 236px;
    border-radius: 7px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, .15);

    &.message-me {
      float: right;
      background-color: #effeff;

      &::before {
        right: -11px;
        background-image: url(/assets/message-me.png);
      }
    }

    &.message-you {
      float: left;
      background-color: #FFF;

      &::before {
        left: -11px;
        background-image: url(/assets/message-you.png);
      }
    }

    &.message-you::before, &.message-me::before {
      content: "";
      position: absolute;
      bottom: 3px;
      width: 12px;
      height: 19px;
      background-position: 50% 50%;
      background-repeat: no-repeat;
      background-size: contain;
    }

    .message-content {
      padding: 5px 7px;
      word-wrap: break-word;

      &::after {
        content: " \00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0";
        display: inline;
      }
    }

    .message-timestamp {
      position: absolute;
      bottom: 2px;
      right: 17px;
      font-size: 11px;
      color: gray;
    }

    .message-timestamp-date {
      position: relative;
      bottom: 2px;
      right: -6px;
      font-size: 9px;
      color: gray;
    }
  }
}

.message-datetime {
    font-size: 11px;
    color: grey;
}

.messages-page-footer {
  padding-right: 0;

  .message-editor {
    margin-left: 2px;
    padding-left: 5px;
    background: white;
    border-radius: 3px;
  }

  .message-editor-button {
    background: color($colors, primary);
    box-shadow: none;
    width: 50px;
    height: 50px;
    font-size: 17px;
    margin: auto;
  }
}

.checkmark {
    display:inline-block;
    width: 22px;
    height:22px;
    -ms-transform: rotate(45deg); /* IE 9 */
    -webkit-transform: rotate(45deg); /* Chrome, Safari, Opera */
    transform: rotate(45deg);
    position: absolute;
    bottom: 2px;
    right: 1px;
}

.checkmark_stem {
    position: absolute;
    width:2px;
    height:9px;
    background-color:#3BB9FF;
    left:15px;
    top:6px;
}

.checkmark_kick {
    position: absolute;
    width:2px;
    height:3px;
    background-color:#3BB9FF;
    left:13px;
    top:12px;
}

.time-tick {
  display:inline-block;
}
</code>```

UPDATE

Thanks to the advise below, I add the following:

CSS

```<code>  .tail-me {
    background-image: url(/assets/message-me.png);
    background-repeat: no-repeat;
    bottom: 0;
    right: -11px
  }

  .tail-you {
    background-image: url(/assets/message-you.png);
    background-repeat: no-repeat;
    bottom: 0;
    left: -11px
  }
</code>```

HTML

```<code><ion-item class="message-item tail-me" *ngFor="let item of firelist | async">
</code>```

And it displays this in the browser:

As you can see, the tail is in the wrong position.  If I make the position: absolute, it throws the message out totally. The left and bottom css attributes move the message bubbles. So I am guessing I am putting the tail-me on the wrong tag in the html. Any ideas?

On an iOS and Android device, it still does not display the tail:

答:
It was a silly mistake on my part. It does work on a devise. The issue was the path to the image was incorrect, so the devise was not picking up the image.

Was:

```<code>background-image: url(/assets/message-me.png);
</code>```

Should be:

```<code>background-image: url(../assets/message-me.png);
</code>```

Title: CSS on device different to browser

Body:
i am using Ionic2 and have an app that has messages. the message looks as follows in a browser:

However, running on an Android or iOS device, it looks as follows:

As you can see, the tail on each message is missing.

Question

If anyone can advise how I can get the style to be consistent and display the tail on all devices?

HTML

<ion-content padding class="messages-page-content">
    <ion-list class="message-list">
      <ion-item class="message-item" *ngFor="let item of firelist | async">

{{item.message_text}}

                        {{item.timestamp | amDateFormat: 'D MMM YY'}}
            {{item.timestamp | amDateFormat: 'h:mm a'}}

      </ion-item>
    </ion-list>
</ion-content>

CSS

See: background-image: url(/assets/message-me.png); and background-image: url(/assets/message-you.png);

.title-timestamp {
  font-size: 11px;
  color: gray;
}

.message-item {
  background-color: transparent;
}

.label {
    overflow: visible;
    white-space: normal;
}

.message-send {
  font-size: 3.2em;
}

.input-wrapper {
    overflow: visible;
}

.item-md.item-block .item-inner {
  padding-left: 8px;
}

.messages-page-navbar {
  .chat-picture {
    width: 50px;
    border-radius: 50%;
    float: left;
  }

  .chat-title {
    line-height: 27px;
    display: inline-block;
  }

  .chat-subtitle {
    font-size: 11px;
    padding: 0px;
  }
}

.messages-page-content {
  > scroll-content {
    padding: 0;
  }

  .message-list {
    background-color: #E0DAD6;
    background-repeat: no-repeat;
    background-size: cover;
  }

  .message-wrapper {
    margin-bottom: 9px;

    &::after {
      content: "";
      display: table;
      clear: both;
    }
  }

  .message {
    display: inline-block;
    position: relative;
    max-width: 236px;
    border-radius: 7px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, .15);

    &.message-me {
      float: right;
      background-color: #effeff;

      &::before {
        right: -11px;
        background-image: url(/assets/message-me.png);
      }
    }

    &.message-you {
      float: left;
      background-color: #FFF;

      &::before {
        left: -11px;
        background-image: url(/assets/message-you.png);
      }
    }

    &.message-you::before, &.message-me::before {
      content: "";
      position: absolute;
      bottom: 3px;
      width: 12px;
      height: 19px;
      background-position: 50% 50%;
      background-repeat: no-repeat;
      background-size: contain;
    }

    .message-content {
      padding: 5px 7px;
      word-wrap: break-word;

      &::after {
        content: " \00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0\00a0";
        display: inline;
      }
    }

    .message-timestamp {
      position: absolute;
      bottom: 2px;
      right: 17px;
      font-size: 11px;
      color: gray;
    }

    .message-timestamp-date {
      position: relative;
      bottom: 2px;
      right: -6px;
      font-size: 9px;
      color: gray;
    }
  }
}

.message-datetime {
    font-size: 11px;
    color: grey;
}

.messages-page-footer {
  padding-right: 0;

  .message-editor {
    margin-left: 2px;
    padding-left: 5px;
    background: white;
    border-radius: 3px;
  }

  .message-editor-button {
    background: color($colors, primary);
    box-shadow: none;
    width: 50px;
    height: 50px;
    font-size: 17px;
    margin: auto;
  }
}

.checkmark {
    display:inline-block;
    width: 22px;
    height:22px;
    -ms-transform: rotate(45deg); /* IE 9 */
    -webkit-transform: rotate(45deg); /* Chrome, Safari, Opera */
    transform: rotate(45deg);
    position: absolute;
    bottom: 2px;
    right: 1px;
}

.checkmark_stem {
    position: absolute;
    width:2px;
    height:9px;
    background-color:#3BB9FF;
    left:15px;
    top:6px;
}

.checkmark_kick {
    position: absolute;
    width:2px;
    height:3px;
    background-color:#3BB9FF;
    left:13px;
    top:12px;
}

.time-tick {
  display:inline-block;
}

UPDATE

Thanks to the advise below, I add the following:

CSS

  .tail-me {
    background-image: url(/assets/message-me.png);
    background-repeat: no-repeat;
    bottom: 0;
    right: -11px
  }

  .tail-you {
    background-image: url(/assets/message-you.png);
    background-repeat: no-repeat;
    bottom: 0;
    left: -11px
  }

HTML

<ion-item class="message-item tail-me" *ngFor="let item of firelist | async">

And it displays this in the browser:

As you can see, the tail is in the wrong position.  If I make the position: absolute, it throws the message out totally. The left and bottom css attributes move the message bubbles. So I am guessing I am putting the tail-me on the wrong tag in the html. Any ideas?

On an iOS and Android device, it still does not display the tail:

Body:
It was a silly mistake on my part. It does work on a devise. The issue was the path to the image was incorrect, so the devise was not picking up the image.

Was:

background-image: url(/assets/message-me.png);

Should be:

background-image: url(../assets/message-me.png);


问:
Is there a way in CSS to calculate line height from em?
Let's say I want an img to be the same height as a line of text.  Is there some way to set this up.  My first thought was something like this:

```
<table>
    <td>
        <img src="pict.png" style="height: 1em"/>
        <img src="pict.png" style="height: 1em"/>
    </td>
    <td>
        The text<br/>
        The second line<br/>
    </td>
</table>
```

However, with that example, the height of the picture is less than the line.   After a few lines the difference becomes very noticeable.  Does anyone have any suggestions?

Also, it looks like for my font 1.15 em is about equal to the line height.  Does this make sense to anyone?

答: I think you need to use JavaScript for this.</p>

Body:
Let's say I want an img to be the same height as a line of text.  Is there some way to set this up.  My first thought was something like this:

        The text

        The second line

However, with that example, the height of the picture is less than the line.   After a few lines the difference becomes very noticeable.  Does anyone have any suggestions?

Also, it looks like for my font 1.15 em is about equal to the line height.  Does this make sense to anyone?

ContentLicense: CC BY-SA 2.5


问:
Do DDL statements always give you an implicit commit, or can you get an implicit rollback?
If you're halfway through a transaction and perform a DDL statement, such as truncating a table, then the transaction commits.

I was wondering whether this was always the case and by definition, or is there a setting hidden somewhere that would rollback the transaction instead of committing.

Thanks.

Edit to clarify...

I'm not looking to rollback after a truncate. I just want to confirm that statements already carried out are absolutely always going to be committed before a DDL. Just want to make sure there isn't a system property somewhere that someone could set to wreck my code.

I understand the need to commit before and after a DDL, but conceptually I'd have thought the same consistency requirement could be achieved with a rollback before the DDL and a commit after.

答:
I agree with DCookie and Tom about the autonomous transaction.  I was going to state this also.

Example pseudocode:

```<code>Do some DML
Call autonomous function, that performs DDL
Do some more DML
rollback or commit all the DML - your choice
</code>```

I don't see this as being very useful though.  If the initial DML and the DDL touch the same table/object, it's not going to work.  You'll get contention when you try to perform the DDL.  Just like any two transactions blocking each other.  And if they're independent objects, I guess I don't see why the execution order matters.

Body:
I agree with DCookie and Tom about the autonomous transaction.  I was going to state this also.

Example pseudocode:

Do some DML
Call autonomous function, that performs DDL
Do some more DML
rollback or commit all the DML - your choice

I don't see this as being very useful though.  If the initial DML and the DDL touch the same table/object, it's not going to work.  You'll get contention when you try to perform the DDL.  Just like any two transactions blocking each other.  And if they're independent objects, I guess I don't see why the execution order matters.


问:
Why is getElementsByTagName returning undefined?
I'm trying to call document.getElementsByTagName, and I'm getting back undefined as a result, no matter what parameter I pass.  (Even if I pass "*".)

I tried Googling for it, but all the search results were about elements of the getElementsByTagName result array being undefined.  What I'm getting is undefined as the result itself, and it's driving me up the wall.

Does anyone know what can cause this?  (Using Firefox 12.0.  In Chrome I get the expected results.)

EDIT: OK, here's sample code:

```<code>function buttonClick(){
   var xhr = new XMLHttpRequest();
   var msg = document.getElementById('message');
   var buttons = document.getElementsByTagName("button");
   var button, i;
   for (i = 0; i < buttons.length; ++i){
      button = buttons[i];
      msg.removeChild(button);
   }

   xhr.onreadystatechange = function() {
        if(xhr.readyState == 4){
            handleResult(xhr.responseText, msg);
        }
   };
   xhr.open("POST", location.href, true);
   xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
   xhr.send("cmd=MyCommand");
}
</code>```

And the getElementsByTagName always returns undefined, whether I trace it in Firebug's Script tab or call it from the Console tab. (Also in Firebug, since this seems to be confusing people.  Apparently there are way too many consoles floating around.).

As proof, here's what I've been getting when I tried to use the Firebug console:

```<code>>>> document.getElementsByTagName("button");
undefined
>>> msg.getElementsByTagName("button");
undefined
>>> msg.getElementsByTagName
getElementsByTagName()
>>> msg.getElementsByTagName("BUTTON");
undefined
>>> msg.getElementsByTagName("*");
undefined
>>> document.getElementsByTagName("*");
undefined
>>> document.getElementsByTagName("body");
undefined
</code>```

The markup is (or ought to be) irrelevant.  It's a valid, well-formed HTML page with some buttons and other elements on it.  This JS function is attached to the onclick of one of the buttons.  But it looks something like this:

```<code><html xmlns="http://www.w3.org/1999/xhtml"><head>
blah
</head>
<body>
<script type="text/javascript" src="/myJS.js"></script>
<div id="page-container">
   <div id="message"><button onclick="buttonClick();">Button 1</button><button onclick="ButtonClick2()">Button 2</button></div>

</div>

</body></html>
</code>```

答:
I got the problem when I made a difficult to see syntax error.  I used parenthesis when I should have used square brackets

Wrong:

```<code>selectedItem._element.childNodes(0).getElementsByTagName('input').item();
</code>```

Right:

```<code>selectedItem._element.childNodes[0].getElementsByTagName('input').item();
</code>```

See the difference?  Note, the top syntax works is older versions of IE, like IE8, but it doesn't work in ie10, ie11, Edge etc

Body:
I'm trying to call document.getElementsByTagName, and I'm getting back undefined as a result, no matter what parameter I pass.  (Even if I pass "*".)

I tried Googling for it, but all the search results were about elements of the getElementsByTagName result array being undefined.  What I'm getting is undefined as the result itself, and it's driving me up the wall.

Does anyone know what can cause this?  (Using Firefox 12.0.  In Chrome I get the expected results.)

EDIT: OK, here's sample code:

function buttonClick(){
   var xhr = new XMLHttpRequest();
   var msg = document.getElementById('message');
   var buttons = document.getElementsByTagName("button");
   var button, i;
   for (i = 0; i < buttons.length; ++i){
      button = buttons[i];
      msg.removeChild(button);
   }

   xhr.onreadystatechange = function() {
        if(xhr.readyState == 4){
            handleResult(xhr.responseText, msg);
        }
   };
   xhr.open("POST", location.href, true);
   xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
   xhr.send("cmd=MyCommand");
}

And the getElementsByTagName always returns undefined, whether I trace it in Firebug's Script tab or call it from the Console tab. (Also in Firebug, since this seems to be confusing people.  Apparently there are way too many consoles floating around.).

As proof, here's what I've been getting when I tried to use the Firebug console:

>>> document.getElementsByTagName("button");
undefined
>>> msg.getElementsByTagName("button");
undefined
>>> msg.getElementsByTagName
getElementsByTagName()
>>> msg.getElementsByTagName("BUTTON");
undefined
>>> msg.getElementsByTagName("*");
undefined
>>> document.getElementsByTagName("*");
undefined
>>> document.getElementsByTagName("body");
undefined

The markup is (or ought to be) irrelevant.  It's a valid, well-formed HTML page with some buttons and other elements on it.  This JS function is attached to the onclick of one of the buttons.  But it looks something like this:

blah

<button onclick="buttonClick();">Button 1</button><button onclick="ButtonClick2()">Button 2</button>

Body:
I got the problem when I made a difficult to see syntax error.  I used parenthesis when I should have used square brackets

Wrong:

selectedItem._element.childNodes(0).getElementsByTagName('input').item();

Right:

selectedItem._element.childNodes[0].getElementsByTagName('input').item();

See the difference?  Note, the top syntax works is older versions of IE, like IE8, but it doesn't work in ie10, ie11, Edge etc


问:
Blank rows not coming
After running the below code i am getting only rows where is present and not the rows where just ID is present.

Is there any problem with the extraction of file.

```<code>DROP VIEW IF EXISTS dbo.Consolidated;
CREATE VIEW IF NOT EXISTS dbo.Consolidated
AS
EXTRACT Statement

FROM   "adl:///2016/08/12/File_name.csv"
USING Extractors.Csv(silent : true, quoting : true, nullEscape : "/N");

@Temp =
SELECT *
FROM Consolidated;

OUTPUT @Temp
TO "adl://arbit/new_cont_check.csv"
USING Outputters.Csv();
</code>```

答:
You have added the silent: true argument to your USING clause meaning the EXTRACT will not fail or even complain if the rows don't quite match your schema definition.  This is the intended behaviour and probably what you want for this example.  In order to pick up the other rows, you can use  OUTER UNION, like in this recent example:

Another working example similar to yours:

```<code>@input =
    EXTRACT ControllerID int?,
            ParameterID int?,
            MeasureDate DateTime,
            Value float
    FROM "/input/input56.csv"
    USING Extractors.Csv(silent : true, quoting : true, nullEscape : "/N", skipFirstNRows : 1)

    OUTER UNION ALL BY NAME ON ( ControllerID )

    EXTRACT ControllerID int?
    FROM "/input/input56.csv"
    USING Extractors.Csv(silent : true, quoting : true, nullEscape : "/N", skipFirstNRows : 1);

OUTPUT @input
TO "/output/output.txt"
USING Outputters.Tsv(quoting : false);
</code>```

I used this sample file and got these results:

NB I have changed the nullability of your columns as otherwise the OUTER UNION add default values for the .Net types as per the Sep 2016 release notes.

ContentLicense: CC BY-SA 4.0

Title: Blank rows not coming

Body:
After running the below code i am getting only rows where is present and not the rows where just ID is present.

Is there any problem with the extraction of file.

DROP VIEW IF EXISTS dbo.Consolidated;
CREATE VIEW IF NOT EXISTS dbo.Consolidated
AS
EXTRACT Statement

FROM   "adl:///2016/08/12/File_name.csv"
USING Extractors.Csv(silent : true, quoting : true, nullEscape : "/N");

@Temp =
SELECT *
FROM Consolidated;

OUTPUT @Temp
TO "adl://arbit/new_cont_check.csv"
USING Outputters.Csv();

Body:
You have added the silent: true argument to your USING clause meaning the EXTRACT will not fail or even complain if the rows don't quite match your schema definition.  This is the intended behaviour and probably what you want for this example.  In order to pick up the other rows, you can use  OUTER UNION, like in this recent example:

Another working example similar to yours:

@input =
    EXTRACT ControllerID int?,
            ParameterID int?,
            MeasureDate DateTime,
            Value float
    FROM "/input/input56.csv"
    USING Extractors.Csv(silent : true, quoting : true, nullEscape : "/N", skipFirstNRows : 1)

    OUTER UNION ALL BY NAME ON ( ControllerID )

    EXTRACT ControllerID int?
    FROM "/input/input56.csv"
    USING Extractors.Csv(silent : true, quoting : true, nullEscape : "/N", skipFirstNRows : 1);

OUTPUT @input
TO "/output/output.txt"
USING Outputters.Tsv(quoting : false);

I used this sample file and got these results:

NB I have changed the nullability of your columns as otherwise the OUTER UNION add default values for the .Net types as per the Sep 2016 release notes.


问:
Malformed matrix while using hstack?
I have the following matrices:

```<code>>>> X1
shape: (2399, 39999)
type: scipy.sparse.csr.csr_matrix
</code>```

And

```<code>>> X2
shape: (2399, 333534)
type: scipy.sparse.csr.csr_matrix
</code>```

And

```<code>>>>X3.reshape(-1,1)
shape: (2399, 1)
type: <class 'numpy.ndarray'>
</code>```

How can I concatenate X1 and X2 by the right side in order to generate a new matrix with the following shape: (2399, 373534). I know that this can be done with scipy's hstack or vstack. However, when I tried to:

```<code>X_combined = sparse.hstack([X1,X2,X3.T])
</code>```

However, I got a malformed final matrix:

```<code>ValueError: all the input array dimensions except for the concatenation axis must match exactly
</code>```

Therefore, how can I concatenate correctly in a single matrix?.

UPDATE

```<code>from sklearn.feature_extraction.text import CountVectorizer
count_vect = CountVectorizer(min_df=5)
X1 = count_vect.fit_transform(X)
</code>```

And

```<code>from sklearn.feature_extraction.text import TfidfVectorizer
tdidf_vect = TfidfVectorizer()
X2 = tdidf_vect.fit_transform(X)
</code>```

And

```<code>from hdbscan import HDBSCAN
clusterer = HDBSCAN().fit(X1)
X3 = clusterer.labels_
print(X3.shape)
print(type(X3))
</code>```

Then:

In:

```<code>import scipy as sparse

X_combined = sparse.hstack([X1,X2,X3.reshape(-1,1)])
</code>```

Out:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-16-14baa47e0993> in <module>()
      5
      6
----> 7 X_combined = sparse.hstack([X1,X2,X3.reshape(-1,1)])

/usr/local/lib/python3.5/site-packages/numpy/core/shape_base.py in hstack(tup)
    284     # As a special case, dimension 0 of 1-dimensional arrays is "horizontal"
    285     if arrs[0].ndim == 1:
--> 286         return _nx.concatenate(arrs, 0)
    287     else:
    288         return _nx.concatenate(arrs, 1)

ValueError: all the input arrays must have same number of dimensions
</code>```

答:
The problem is your import, it should be

```<code>from scipy import sparse
</code>```

The top-level scipy module (normally you shouldn't use the top-level scipy module anyway) imports the numpy functions, so when you try your version:

```<code>>>> import scipy as sparse
>>> sparse.hstack
<function numpy.core.shape_base.hstack>

>>> # incorrect! Correct would be

>>> from scipy import sparse
>>> sparse.hstack
<function scipy.sparse.construct.hstack>
</code>```

This is all mentioned in their documentation:

The scipy namespace itself only contains functions imported from numpy. These functions still exist for backwards compatibility, but should be imported from numpy directly.

Everything in the namespaces of scipy submodules is public. In general, it is recommended to import functions from submodule namespaces.

Title: Malformed matrix while using hstack?

Body:
I have the following matrices:

>>> X1
shape: (2399, 39999)
type: scipy.sparse.csr.csr_matrix

And

>> X2
shape: (2399, 333534)
type: scipy.sparse.csr.csr_matrix

And

>>>X3.reshape(-1,1)
shape: (2399, 1)
type: <class 'numpy.ndarray'>

How can I concatenate X1 and X2 by the right side in order to generate a new matrix with the following shape: (2399, 373534). I know that this can be done with scipy's hstack or vstack. However, when I tried to:

X_combined = sparse.hstack([X1,X2,X3.T])

However, I got a malformed final matrix:

ValueError: all the input array dimensions except for the concatenation axis must match exactly

Therefore, how can I concatenate correctly in a single matrix?.

UPDATE

from sklearn.feature_extraction.text import CountVectorizer
count_vect = CountVectorizer(min_df=5)
X1 = count_vect.fit_transform(X)

And

from sklearn.feature_extraction.text import TfidfVectorizer
tdidf_vect = TfidfVectorizer()
X2 = tdidf_vect.fit_transform(X)

And

from hdbscan import HDBSCAN
clusterer = HDBSCAN().fit(X1)
X3 = clusterer.labels_
print(X3.shape)
print(type(X3))

Then:

In:

import scipy as sparse

X_combined = sparse.hstack([X1,X2,X3.reshape(-1,1)])

Out:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-16-14baa47e0993> in <module>()
      5
      6
----> 7 X_combined = sparse.hstack([X1,X2,X3.reshape(-1,1)])

/usr/local/lib/python3.5/site-packages/numpy/core/shape_base.py in hstack(tup)
    284     # As a special case, dimension 0 of 1-dimensional arrays is "horizontal"
    285     if arrs[0].ndim == 1:
--> 286         return _nx.concatenate(arrs, 0)
    287     else:
    288         return _nx.concatenate(arrs, 1)

ValueError: all the input arrays must have same number of dimensions

Body:
The problem is your import, it should be

from scipy import sparse

The top-level scipy module (normally you shouldn't use the top-level scipy module anyway) imports the numpy functions, so when you try your version:

>>> import scipy as sparse
>>> sparse.hstack
<function numpy.core.shape_base.hstack>

>>> # incorrect! Correct would be

>>> from scipy import sparse
>>> sparse.hstack
<function scipy.sparse.construct.hstack>

This is all mentioned in their documentation:

The scipy namespace itself only contains functions imported from numpy. These functions still exist for backwards compatibility, but should be imported from numpy directly.

Everything in the namespaces of scipy submodules is public. In general, it is recommended to import functions from submodule namespaces.


问:
image processing
How is image processing done?

I want to compare two images and identify the differences between them. How do I identify difference between two taken pixels of different images?

答:
Don't simply add the differences from Answer 1, or positive and negative differences will cancel out! You need to sum the squares of the differences, or their absolute values.
You could also consider multiplying the pairs of pixels and dividing by their sum (correlation).

All three of these methods are now technically correct but they will still be far from practically useful. Don't be surprised to find smaller difference between two totally unrelated images than, say, two images of the same object with a slightly different illumination.

Title: image processing


问:
How to not show a mobile keyboard when using bootstrap-datepicker?
I tried setting the disableTouchKeyboard option but it did nothing -- at least on iOS/Safari. The options I was specifically using were:

```<code>$(".datepicker").datepicker({
    autoclose: true,
    disableTouchKeyboard: true,
    format: 'm/d/yyyy',
    startDate: '01/01/1900',
    todayBtn: 'linked',
    todayHighlight: true,
});
</code>```

Anyone know what the best way to do this is?

答:
This is an old question but I thought I should share my solution since this question shows up in Google search. If you make the input type a button the keyboard will not show up and you can style the button to look like a text input field if you really need to.</p>

```<code><input type="button" style="background-color:white;border:1px solid #DDD;padding:5px;cursor:text;" value="Enter a Date" id="datepicker">
</code>```

Body:
I tried setting the disableTouchKeyboard option but it did nothing -- at least on iOS/Safari. The options I was specifically using were:

$(".datepicker").datepicker({
    autoclose: true,
    disableTouchKeyboard: true,
    format: 'm/d/yyyy',
    startDate: '01/01/1900',
    todayBtn: 'linked',
    todayHighlight: true,
});

Anyone know what the best way to do this is?

Body:
This is an old question but I thought I should share my solution since this question shows up in Google search. If you make the input type a button the keyboard will not show up and you can style the button to look like a text input field if you really need to.

<input type="button" style="background-color:white;border:1px solid #DDD;padding:5px;cursor:text;" value="Enter a Date" id="datepicker">


问:
How do I substitute one word in a string variable in Python?
I know people have asked about how to substitute words in strings, but I'd like to replace a specific word in a variable string, and leave the rest untouched.

For example: if the user enters "My family does not like chicken", I'd like the computer to output back to them "Your family does not like chicken". The word being replaced is "My", and the word replacing it is "Your". I'm using Python 2.7.13.

答:
Use the replace() function

```<code>oldstr = 'my family does not like chicken'
newstr = oldstr.replace('my', 'your')
print(newstr)
</code>```

Output
    your family does not like chicken

Body:
Use the replace() function

oldstr = 'my family does not like chicken'
newstr = oldstr.replace('my', 'your')
print(newstr)

Output
    your family does not like chicken


问:
Is there a way to bundle a binary file (such as chromedriver) with a single file app/exe compiled with Pyinstaller?
As noted in the answer to my question here, setting the path to chromedriver in binaries in the Pyinstaller spec file (binaries=[('/usr/bin/chromedriver', './selenium/webdriver')]) didn’t have an effect (unless it was set incorrectly). That is, chromedriver is accessed as long as it’s in the PATH (/usr/bin in this case). My question regards the possibility to bundle chromedriver in the background so that it doesn’t have to be manually installed on another machine.

答:
I succesfully bundled chromedriver with pyinstaller (although unfortunately, my virusscanner flagged it, after I ran the exe, but that's another problem)

I guess your problem is that you do not give the correct path to the webdriver in the script (using keyword executable_path). Also, I included the chromedriver as a data-file, although I'm not sure if that makes a difference..

Here is my example.

sel_ex.py:

```<code>from selenium import webdriver

import os, sys, inspect     # http://stackoverflow.com/questions/279237/import-a-module-from-a-relative-path
current_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe() ))[0]))

def init_driver():
    chromedriver = os.path.join(current_folder,"chromedriver.exe")
    # via this way, you explicitly let Chrome know where to find
    # the webdriver.
    driver = webdriver.Chrome(executable_path = chromedriver)
    return driver

if __name__ == "__main__":
    driver = init_driver()
    driver.get("http://www.imdb.com/")
</code>```

sel_ex.spec:

```<code>....
binaries=[],
datas=[("chromedriver.exe",".")],
....
</code>```

In this way, the chromedriver was stored in the main folder, although it should not matter where it is stored, as long as the script correct path through the keyword executable_path

disclaimers:
-I did not use the one-file-settings, but that shouldn't make a difference.
-my OS is windows

Body:
I succesfully bundled chromedriver with pyinstaller (although unfortunately, my virusscanner flagged it, after I ran the exe, but that's another problem)

I guess your problem is that you do not give the correct path to the webdriver in the script (using keyword executable_path). Also, I included the chromedriver as a data-file, although I'm not sure if that makes a difference..

Here is my example.

sel_ex.py:

from selenium import webdriver

import os, sys, inspect     # http://stackoverflow.com/questions/279237/import-a-module-from-a-relative-path
current_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe() ))[0]))

def init_driver():
    chromedriver = os.path.join(current_folder,"chromedriver.exe")
    # via this way, you explicitly let Chrome know where to find
    # the webdriver.
    driver = webdriver.Chrome(executable_path = chromedriver)
    return driver

if __name__ == "__main__":
    driver = init_driver()
    driver.get("http://www.imdb.com/")

sel_ex.spec:

....
binaries=[],
datas=[("chromedriver.exe",".")],
....

In this way, the chromedriver was stored in the main folder, although it should not matter where it is stored, as long as the script correct path through the keyword executable_path

disclaimers:
-I did not use the one-file-settings, but that shouldn't make a difference.
-my OS is windows


问:
Why do these sum operations not "add up" as they should?
Note: This is a follow[on,up] to this question and this question and this question.

The responses all moved me forward, but even that last one, although it improved matters, did not completely solve this issue.

This query:

```<code>select monthlysales, MemberNo from ReportingMonthlySales
where unit = 'Abuelos' and CYear = 2017 and cmonth = 3
</code>```

...returns a bunch of rows, where the Monthly Sales total is $364,121.69

However, when I try to compartmentalize these monthly sales into four categories, although the sum of them all should be the same, the sum is actually astronomically "huger" - the following code returns the vastly inflated value of 23,924,211.30

24 millions of dollars is almost 70 times as much as the 364 thousand that is the actual sum total. Why is this "crazy" inflation occurring?

Here is the fancy pants but apparently bamboozled code:

```<code>declare @Unit varchar(30);
declare @Year int = 2017;
declare @Month int = 3;
declare @paramdate datetime;
set @paramdate = convert(datetime,convert(char(4),@Year)
                +right('0'+convert(varchar(2),@month),2)
                +'01')

IF OBJECT_ID('tempdb.dbo.#Units', 'U') IS NOT NULL
DROP TABLE #Units

select distinct unit
into #Units
from ReportingMonthlySales;

select
    u.Unit
  , New      = sum(case when ccl.Subcategory = 'New'      then rms.MonthlySales else 0 end)
  , Assumed  = sum(case when ccl.Subcategory = 'Assumed'  then rms.MonthlySales else 0 end)
  , Existing = sum(case when ccl.Subcategory = 'Existing' then rms.MonthlySales else 0 end)
  , Organic  = sum(case when ccl.Subcategory = 'Organic'  then rms.MonthlySales else 0 end)
from #Units u
  left join CustomerCategoryLog ccl
    on u.Unit = ccl.Unit
   and @paramdate >= ccl.begindate and
   (@paramdate <= ccl.enddate OR ccl.enddate is null)
  left join ReportingMonthlySales rms
    on u.Unit = rms.Unit
   and rms.cyear  = @year
   and rms.cmonth = @month
group by u.unit;

The two tables queried are:

CustomerCategoryLog
-------------------
MemberNo (VarChar)
Unit (VarChar)
Custno (VarChar)
Category (VarChar)
Subcategory (VarChar)
BeginDate (DateTime)
EndDate (DateTime)
ChangedBy (VarChar)
ChangedOn (DateTime)

ReportingMonthlySales
---------------------
AutoID (Int)
Unit (VarChar)
MemberNo (VarChar)
NumUnits (Int)
MonthlySales (Money)
CYear (Int)
Cmonth (Int)
CreateDate (DateTime)
</code>```

Is there something faulty in the fancy-pants sql, or ... ?!?

答:
I suspect the left joins and Or ccl.enddate is null generated a 1 to many

Perhaps a straight inner join will correct the inflation

```<code>select
    u.Unit
  , New      = sum(case when ccl.Subcategory = 'New'      then rms.MonthlySales else 0 end)
  , Assumed  = sum(case when ccl.Subcategory = 'Assumed'  then rms.MonthlySales else 0 end)
  , Existing = sum(case when ccl.Subcategory = 'Existing' then rms.MonthlySales else 0 end)
  , Organic  = sum(case when ccl.Subcategory = 'Organic'  then rms.MonthlySales else 0 end)
from #Units u
join CustomerCategoryLog   ccl on u.Unit = ccl.Unit and @paramdate >= ccl.begindate and @paramdate <= ccl.enddate
join ReportingMonthlySales rms on u.Unit = rms.Unit and rms.cyear  = @year and rms.cmonth = @month
group by u.unit;
</code>```

Body:
Note: This is a follow[on,up] to this question and this question and this question.

The responses all moved me forward, but even that last one, although it improved matters, did not completely solve this issue.

This query:

select monthlysales, MemberNo from ReportingMonthlySales
where unit = 'Abuelos' and CYear = 2017 and cmonth = 3

...returns a bunch of rows, where the Monthly Sales total is $364,121.69

However, when I try to compartmentalize these monthly sales into four categories, although the sum of them all should be the same, the sum is actually astronomically "huger" - the following code returns the vastly inflated value of 23,924,211.30

24 millions of dollars is almost 70 times as much as the 364 thousand that is the actual sum total. Why is this "crazy" inflation occurring?

Here is the fancy pants but apparently bamboozled code:

declare @Unit varchar(30);
declare @Year int = 2017;
declare @Month int = 3;
declare @paramdate datetime;
set @paramdate = convert(datetime,convert(char(4),@Year)
                +right('0'+convert(varchar(2),@month),2)
                +'01')

IF OBJECT_ID('tempdb.dbo.#Units', 'U') IS NOT NULL
DROP TABLE #Units

select distinct unit
into #Units
from ReportingMonthlySales;

select
    u.Unit
  , New      = sum(case when ccl.Subcategory = 'New'      then rms.MonthlySales else 0 end)
  , Assumed  = sum(case when ccl.Subcategory = 'Assumed'  then rms.MonthlySales else 0 end)
  , Existing = sum(case when ccl.Subcategory = 'Existing' then rms.MonthlySales else 0 end)
  , Organic  = sum(case when ccl.Subcategory = 'Organic'  then rms.MonthlySales else 0 end)
from #Units u
  left join CustomerCategoryLog ccl
    on u.Unit = ccl.Unit
   and @paramdate >= ccl.begindate and
   (@paramdate <= ccl.enddate OR ccl.enddate is null)
  left join ReportingMonthlySales rms
    on u.Unit = rms.Unit
   and rms.cyear  = @year
   and rms.cmonth = @month
group by u.unit;

The two tables queried are:

CustomerCategoryLog
-------------------
MemberNo (VarChar)
Unit (VarChar)
Custno (VarChar)
Category (VarChar)
Subcategory (VarChar)
BeginDate (DateTime)
EndDate (DateTime)
ChangedBy (VarChar)
ChangedOn (DateTime)

ReportingMonthlySales
---------------------
AutoID (Int)
Unit (VarChar)
MemberNo (VarChar)
NumUnits (Int)
MonthlySales (Money)
CYear (Int)
Cmonth (Int)
CreateDate (DateTime)

Is there something faulty in the fancy-pants sql, or ... ?!?

Body:
I suspect the left joins and Or ccl.enddate is null generated a 1 to many

Perhaps a straight inner join will correct the inflation

select
    u.Unit
  , New      = sum(case when ccl.Subcategory = 'New'      then rms.MonthlySales else 0 end)
  , Assumed  = sum(case when ccl.Subcategory = 'Assumed'  then rms.MonthlySales else 0 end)
  , Existing = sum(case when ccl.Subcategory = 'Existing' then rms.MonthlySales else 0 end)
  , Organic  = sum(case when ccl.Subcategory = 'Organic'  then rms.MonthlySales else 0 end)
from #Units u
join CustomerCategoryLog   ccl on u.Unit = ccl.Unit and @paramdate >= ccl.begindate and @paramdate <= ccl.enddate
join ReportingMonthlySales rms on u.Unit = rms.Unit and rms.cyear  = @year and rms.cmonth = @month
group by u.unit;


问:
jQuery UI autocomplete gets very slow with long list of items
I have a list of around 8,000 items (loading from MySQL) and I made a simple HTML select field to load all of them but the load time was more than 10-15 seconds every time. Then i changed it to jQuery autocomplete which is much better than simple select field but the delay is still 8-10 seconds everytime. Is there any way to decrease the load time?

I try this method jQuery UI Autocomplete Combobox Very Slow With Large Select Lists but it doesn't affect the loading speed

答:
You can also try html5 datalist

```<code><input list="browsers" name="browser">
  <datalist id="browsers">
    <option value="Internet Explorer">
    <option value="Firefox">
    <option value="Chrome">
    <option value="Opera">
    <option value="Safari">
  </datalist>
</code>```

and you can also try light weight js http://leaverou.github.io/awesomplete/

Body:
You can also try html5 datalist

<input list="browsers" name="browser">
  <datalist id="browsers">
    <option value="Internet Explorer">
    <option value="Firefox">
    <option value="Chrome">
    <option value="Opera">
    <option value="Safari">
  </datalist>

and you can also try light weight js http://leaverou.github.io/awesomplete/


问:
Docker communication between two containers with Java
There are two java files, Server.java and Client.java.
Both are in separate containers.

DOCKER FILES:
The dockerfile(in the folder named 'Server') that i use for server is:

```<code>FROM java:8
COPY Server.java /
RUN javac Server.java
EXPOSE 25000
ENTRYPOINT ["java"]
CMD ["Server"]
</code>```

The dockerfile(in the folder named 'Client') for client is:

```<code>FROM java:8
COPY Client.java /
RUN javac Client.java
EXPOSE 25000
ENTRYPOINT ["java"]
CMD ["Client"]
</code>```

BUILDING THE CONTAINERS:
Building the containers using sudo docker build -t serverimage .

RUNNING THE CONTAINERS:
I run the images using the command sudo docker run <IMAGE_NAME>.And I am running the serverimage first.

The error i am getting(When i run clientimage) is:

```<code>java.net.ConnectException: Connection refused: connect
</code>```

Server.java File:

```<code>import java.io.*;
import java.net.*;
public class MyServer {
   public static void main(String[] args){
       try{
           ServerSocket ss=new ServerSocket(25000);
           Socket s=ss.accept();//establishes connection
           DataInputStream dis=new DataInputStream(s.getInputStream());
           String  str=(String)dis.readUTF();
           System.out.println("message= "+str);
           ss.close();
       }catch(Exception e){System.out.println(e);}
   }
}
</code>```

Client.java File:

```<code>import java.io.*;
import java.net.*;
public class MyClient {
   public static void main(String[] args) {
      try{
         Socket s=new Socket("localhost",25000);
         DataOutputStream dout=new DataOutputStream(s.getOutputStream());
         dout.writeUTF("Hello Server");
         dout.flush();
         dout.close();
         s.close();
      }catch(Exception e){System.out.println(e);}
   }
}
</code>```

What am I possibly doing wrong?
Thank you!

答:
There are 3 problems:

The classes should be named Server and Client, or else the Server.java & Client.Java files should be named MyServer.java & MyClient.java, respectively.

When you create a Docker container, 2 interfaces are created: localhost and another interface for communicating with other containers.  You should change "localhost" to the server container IP or the host IP.

The java images are deprecated.

Also, there's no need for the EXPOSE directive in the client Dockerfile.

Body:
There are two java files, Server.java and Client.java.
Both are in separate containers.

DOCKER FILES:
The dockerfile(in the folder named 'Server') that i use for server is:

FROM java:8
COPY Server.java /
RUN javac Server.java
EXPOSE 25000
ENTRYPOINT ["java"]
CMD ["Server"]

The dockerfile(in the folder named 'Client') for client is:

FROM java:8
COPY Client.java /
RUN javac Client.java
EXPOSE 25000
ENTRYPOINT ["java"]
CMD ["Client"]

BUILDING THE CONTAINERS:
Building the containers using sudo docker build -t serverimage .

RUNNING THE CONTAINERS:
I run the images using the command sudo docker run <IMAGE_NAME>.And I am running the serverimage first.

The error i am getting(When i run clientimage) is:

java.net.ConnectException: Connection refused: connect

Server.java File:

import java.io.*;
import java.net.*;
public class MyServer {
   public static void main(String[] args){
       try{
           ServerSocket ss=new ServerSocket(25000);
           Socket s=ss.accept();//establishes connection
           DataInputStream dis=new DataInputStream(s.getInputStream());
           String  str=(String)dis.readUTF();
           System.out.println("message= "+str);
           ss.close();
       }catch(Exception e){System.out.println(e);}
   }
}

Client.java File:

import java.io.*;
import java.net.*;
public class MyClient {
   public static void main(String[] args) {
      try{
         Socket s=new Socket("localhost",25000);
         DataOutputStream dout=new DataOutputStream(s.getOutputStream());
         dout.writeUTF("Hello Server");
         dout.flush();
         dout.close();
         s.close();
      }catch(Exception e){System.out.println(e);}
   }
}

What am I possibly doing wrong?
Thank you!


问:
using count and group by correctly
I have a relation CandyC(id, email, age, name, candy_id)
I want to count the CandyC.ids associated with a CandyC.candy_id once.

Attempt:

```<code>SELECT email, age, name
FROM CandyC
GROUP BY id
HAVING COUNT(DISTINCT candy_id) = 1;
</code>```

It gives me an error:
not a group by expression

答:
I think you want something more like this:

```<code>SELECT candy_id, COUNT(*)
FROM CandyC
GROUP BY candy_id;
</code>```

I don't know what the email/age/name columns have to do with the question:

I want to count the CandyC.ids associated with a CandyC.candy_id once.

Title: using count and group by correctly

Body:
I have a relation CandyC(id, email, age, name, candy_id)
I want to count the CandyC.ids associated with a CandyC.candy_id once.

Attempt:

SELECT email, age, name
FROM CandyC
GROUP BY id
HAVING COUNT(DISTINCT candy_id) = 1;

It gives me an error:
not a group by expression

Body:
I think you want something more like this:

SELECT candy_id, COUNT(*)
FROM CandyC
GROUP BY candy_id;

I don't know what the email/age/name columns have to do with the question:

I want to count the CandyC.ids associated with a CandyC.candy_id once.


问:
Initialization of an ArrayList in one line
I wanted to create a list of options for testing purposes. At first, I did this:

```<code>ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");
</code>```

Then, I refactored the code as follows:

```<code>ArrayList<String> places = new ArrayList<String>(
    Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
</code>```

Is there a better way to do this?

答:
You can use the below statements:

Code Snippet:

```<code>String [] arr = {"Sharlock", "Homes", "Watson"};

List<String> names = Arrays.asList(arr);
</code>```

Body:
I wanted to create a list of options for testing purposes. At first, I did this:

ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");

Then, I refactored the code as follows:

ArrayList<String> places = new ArrayList<String>(
    Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

Is there a better way to do this?

Body:
You can use the below statements:

Code Snippet:

String [] arr = {"Sharlock", "Homes", "Watson"};

List<String> names = Arrays.asList(arr);


问:
JavaScript - Dropdown value dependent
I have two dropdown right now. I want to when the user selects "NO" the other automatically selects "YES" and vice versa.

I'm assuming I use JS here to make this occur, but not sure where to start. Below is my dropdown html code. If someone could help me get started, it would be helpful.

Code:

Currently:
    <select id="cmicrophone" name="cmicrophone">
     <option value=" " selected = "selected"> </option>
     <option value="on">ON</option>
     <option value="off">OFF</option>
    </select>

Microphone:
    <select id="microphone" name = "microphone">
     <option value=" " selected="selected"> </option>
     <option value="on" >ON</option>
     <option value="off">OFF</option>
    </select>
   </div```

答:
Here's a vanilla JS solution (no jquery required).

The idea here is to:

select both <select> elements and save them into variables to refer to later using document.querySelector

add input event listeners on both elements that call a function to handle the event

then use inside the function selectElement.selectedIndex to check the selected index of one element and use that to set the value of the other.

// select the `<select>` elements
const cmicrophone = document.querySelector('#cmicrophone');
const microphone = document.querySelector('#microphone');

// define function to handler the events
function inputHandler(thisSelect, otherSelect) {
  if (thisSelect.selectedIndex == 1) {
    otherSelect.selectedIndex = 2;
  } else if (thisSelect.selectedIndex == 2) {
    otherSelect.selectedIndex = 1;
  } else {
    thisSelect.selectedIndex = 0;
    otherSelect.selectedIndex = 0;
  }
}

// add event listeners that will 'fire' when the input of the <select> changes
cmicrophone.addEventListener('input', event => {
  inputHandler(cmicrophone, microphone);
});

microphone.addEventListener('input', event => {
  inputHandler(microphone, cmicrophone);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>Currently:
  <select id="cmicrophone" name="cmicrophone">
    <option value=" " selected = "selected"> </option>
    <option value="on">ON</option>
    <option value="off">OFF</option>
  </select>
</div>
<div>Microphone:
  <select id="microphone" name="microphone">
    <option value=" " selected="selected"> </option>
    <option value="on" >ON</option>
    <option value="off">OFF</option>
  </select>
</div></code>```

One more thing to add: You assigned the same value to multiple ids. You should only assign one unique id per element.

Title: JavaScript - Dropdown value dependent

Body:
Here's a vanilla JS solution (no jquery required).

The idea here is to:

select both <select> elements and save them into variables to refer to later using document.querySelector

add input event listeners on both elements that call a function to handle the event

then use inside the function selectElement.selectedIndex to check the selected index of one element and use that to set the value of the other.

// select the `<select>` elements
const cmicrophone = document.querySelector('#cmicrophone');
const microphone = document.querySelector('#microphone');

// define function to handler the events
function inputHandler(thisSelect, otherSelect) {
  if (thisSelect.selectedIndex == 1) {
    otherSelect.selectedIndex = 2;
  } else if (thisSelect.selectedIndex == 2) {
    otherSelect.selectedIndex = 1;
  } else {
    thisSelect.selectedIndex = 0;
    otherSelect.selectedIndex = 0;
  }
}

// add event listeners that will 'fire' when the input of the <select> changes
cmicrophone.addEventListener('input', event => {
  inputHandler(cmicrophone, microphone);
});

microphone.addEventListener('input', event => {
  inputHandler(microphone, cmicrophone);
});

<div>Currently:
  <select id="cmicrophone" name="cmicrophone">
    <option value=" " selected = "selected"> </option>
    <option value="on">ON</option>
    <option value="off">OFF</option>
  </select>
</div>
<div>Microphone:
  <select id="microphone" name="microphone">
    <option value=" " selected="selected"> </option>
    <option value="on" >ON</option>
    <option value="off">OFF</option>
  </select>
</div>

One more thing to add: You assigned the same value to multiple ids. You should only assign one unique id per element.


问:
scrollToRowAtIndexPath:atScrollPosition: not work in autolayout
Storyboard with autolayout

```<code>self.couponTableViewHeightConstraint.const = [self.coupons count] * cellHeight;
[self.couponTableView scrollToRowAtIndexPath:selectedIndexPath
                                    atScrollPosition:UITableViewScrollPositionNone
                                            animated:NO];
</code>```

Not work!

答:
If you are using scrollToRowAtIndexPath:selectedIndexPath be sure you don't use it in viewdidload or viewwillappear. Otherwise you are calling the method before uitableview is rendered.

Use it in viewDidLayoutSubviews instead.

Body:
Storyboard with autolayout

self.couponTableViewHeightConstraint.const = [self.coupons count] * cellHeight;
[self.couponTableView scrollToRowAtIndexPath:selectedIndexPath
                                    atScrollPosition:UITableViewScrollPositionNone
                                            animated:NO];

Not work!


问:
Creating a Function that works for 2 models in Rails
I have two models which need an identical function. I'd like to learn how to make this DRY the right rails way...

For both models I have:

```<code>before_save :assign_uuid
</code>```

Which in each model has:

```<code>  def assign_uuid
    if self.uuid.nil?
      self.uuid = ActiveSupport::SecureRandom.hex(32)
    end
  end
</code>```

Since, assign_uuid lives in both models, Where is the one place I should place this func? Also, in the models, where it say's before_save. How do I call the assign_uuid in the location it is located?

Thanks

答: You should add this as a module and mix it into your models, that is the Ruby way to do what you are after.</p>

Body:
I have two models which need an identical function. I'd like to learn how to make this DRY the right rails way...

For both models I have:

before_save :assign_uuid

Which in each model has:

  def assign_uuid
    if self.uuid.nil?
      self.uuid = ActiveSupport::SecureRandom.hex(32)
    end
  end

Since, assign_uuid lives in both models, Where is the one place I should place this func? Also, in the models, where it say's before_save. How do I call the assign_uuid in the location it is located?

Thanks


问:
Failed to instantiate the default view controller for UIMainStoryboardFile 'Main'
I am trying to create a new Swift project and am having some issues. I tried to create a new single page application but when I build I get an error saying:

```<code>2014-06-07 11:04:13.752 Matchismo (Swift)[2007:598021] Failed to instantiate
the default view controller for UIMainStoryboardFile 'Main' - perhaps the
designated entry point is not set?
</code>```

But when I create the same single page application project with Objective-C as the language, it compiles and runs just fine. Is there some manual thing I must do in Swift to get a project up and running?

My understanding for this error is that I need the default view to be set, which is merely checking a box on your view controller's attributes (picture below). I tried the solution suggested in this stackoverflow post but it didnt help and I can't find much more help on the subject with Swift being so new. Any suggestions are appreciated.

答: Select the ViewController Scene. Now, select the inspector panel from the sidebar options. Check the “Is Initial View Controller” attribute option, save the project and build the project again.</p>

Body:
I am trying to create a new Swift project and am having some issues. I tried to create a new single page application but when I build I get an error saying:

2014-06-07 11:04:13.752 Matchismo (Swift)[2007:598021] Failed to instantiate
the default view controller for UIMainStoryboardFile 'Main' - perhaps the
designated entry point is not set?

But when I create the same single page application project with Objective-C as the language, it compiles and runs just fine. Is there some manual thing I must do in Swift to get a project up and running?

My understanding for this error is that I need the default view to be set, which is merely checking a box on your view controller's attributes (picture below). I tried the solution suggested in this stackoverflow post but it didnt help and I can't find much more help on the subject with Swift being so new. Any suggestions are appreciated.


问:
Android instrumented test no tests found
I am new to Android instrumented unit tests. I have a simple test that looks like this. This is in instrumented tests; before I really write an actual instrumented test, I just want to test a simple one:

```<code>@RunWith(AndroidJUnit4.class)
@SmallTest
public class AddressBookKeepingInstrumentedTest {

    public static final String TEST_STRING = "This is a string";
    public static final long TEST_LONG = 12345678L;

    @Test
    public void test_simple() {
        assertEquals(2,1+1);
    }
}
</code>```

When I run this, I get the following error:

```<code>junit.framework.AssertionFailedError: No tests found in com.example.myfirstapp.AddressBookKeepingInstrumentedTest
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1729)

Tests ran to completion.
</code>```

Gradle build passed with success before this.
Any ideas why this is happening?

答: This post helped me, just rename your tests methods with "test...", like testMethod()

Body:
I am new to Android instrumented unit tests. I have a simple test that looks like this. This is in instrumented tests; before I really write an actual instrumented test, I just want to test a simple one:

@RunWith(AndroidJUnit4.class)
@SmallTest
public class AddressBookKeepingInstrumentedTest {

    public static final String TEST_STRING = "This is a string";
    public static final long TEST_LONG = 12345678L;

    @Test
    public void test_simple() {
        assertEquals(2,1+1);
    }
}

When I run this, I get the following error:

junit.framework.AssertionFailedError: No tests found in com.example.myfirstapp.AddressBookKeepingInstrumentedTest
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1729)

Tests ran to completion.

Gradle build passed with success before this.
Any ideas why this is happening?


问:
Background image on div isn't rendering
I've been trying to apply a simple background image to a div. It seems like such a simple problem but after hours of searching through many threads on Stack and other sources, and trying many of the solutions, i'm still looking at an empty div.

I've verified that the asterisk.png file exists and renders when called by itself from an  tag.

Here is the HTML

```<code>  <div class="element"></div>
</code>```

Here is the CSS

```<code>.element{
  background-image: url('images/asterisk.png');
  background-repeat: repeat-x;
  width: 400px;
  height: 50px;
}
</code>```

Im hoping someone can point out the simple error I'm making here ... Thanks!

答:
It should work, check in inspector if any other styles are not added to this element.
Something may make your element display: inline in this case, yes BG will be not visible, change it to display block or inline-block

Title: Background image on div isn't rendering

Body:
I've been trying to apply a simple background image to a div. It seems like such a simple problem but after hours of searching through many threads on Stack and other sources, and trying many of the solutions, i'm still looking at an empty div.

I've verified that the asterisk.png file exists and renders when called by itself from an  tag.

Here is the HTML

Here is the CSS

.element{
  background-image: url('images/asterisk.png');
  background-repeat: repeat-x;
  width: 400px;
  height: 50px;
}

Im hoping someone can point out the simple error I'm making here ... Thanks!