问:
Basic setup of react-big-calendar events not showing
Im trying to use the react-big-calendar package. http://intljusticemission.github.io/react-big-calendar/examples/index.html </p>

<p>I have the calendar displaying on the page. The pagination is working and I have no errors in my console. However none of my events are showing. Do I have a syntax / format error somewhere? </p>

```<code>import React from 'react';
import BigCalendar from 'react-big-calendar';
import moment from 'moment';

BigCalendar.momentLocalizer(moment); // or globalizeLocalizer

const Calendar = props => {
  const dummyEvents = [
    {
      allDay: false,
      end: new Date('December 10, 2017 11:13:00'),
      start: new Date('December 09, 2017 11:13:00'),
      title: 'hi',
    },
    {
      allDay: true,
      end: new Date('December 09, 2017 11:13:00'),
      start: new Date('December 09, 2017 11:13:00'),
      title: 'All Day Event',
    },
  ];
  return (
     <div>
         <BigCalendar
          events={dummyEvents}
          startAccessor="startDate"
          endAccessor="endDate"
        />
     </div>
  )
}
</code>```

答:
You need to set a height or min height on the calendar:</p>

```<code>.rbc-calendar {
  min-height: 600px;
}

const dummyEvents = [
    {
      allDay: false,
      end: new Date('December 09, 2017 20:00:00'),
      start: new Date('December 09, 2017 06:00:00'),
      title: 'hi',
    }
]
</code>```

Body:
Im trying to use the react-big-calendar package. http://intljusticemission.github.io/react-big-calendar/examples/index.html

I have the calendar displaying on the page. The pagination is working and I have no errors in my console. However none of my events are showing. Do I have a syntax / format error somewhere?

import React from 'react';
import BigCalendar from 'react-big-calendar';
import moment from 'moment';

BigCalendar.momentLocalizer(moment); // or globalizeLocalizer

const Calendar = props => {
  const dummyEvents = [
    {
      allDay: false,
      end: new Date('December 10, 2017 11:13:00'),
      start: new Date('December 09, 2017 11:13:00'),
      title: 'hi',
    },
    {
      allDay: true,
      end: new Date('December 09, 2017 11:13:00'),
      start: new Date('December 09, 2017 11:13:00'),
      title: 'All Day Event',
    },
  ];
  return (

         <BigCalendar
          events={dummyEvents}
          startAccessor="startDate"
          endAccessor="endDate"
        />

  )
}

Body:
You need to set a height or min height on the calendar:

.rbc-calendar {
  min-height: 600px;
}

const dummyEvents = [
    {
      allDay: false,
      end: new Date('December 09, 2017 20:00:00'),
      start: new Date('December 09, 2017 06:00:00'),
      title: 'hi',
    }
]


来源: stackexchange

问:
Paypal suddenly doesn't call "onAuthorize" method during express checkout
My problem today is that I have a web application with an express checkout to execute.
I used the Client - Server architecture to avoid security issues.
So my client code is the following:

```<code>paypal.Button.render({

        env : 'sandbox',
        commit: true,
        style: {
            size: 'medium',
            color: 'gold',
            shape: 'pill',
            label: 'checkout'
        },
        locale: 'en_US',
        payment: function() {
            nickname = $("#nickname").val();
            amount = $("#amount").val();
            description = $("#description").val();
            data = {
                "nickname" : nickname,
                "amount" : amount,
                "description" : description
            };
            return new paypal.Promise(function(resolve, reject) {

                // Call your server side to get the Payment ID from step 3, then pass it to the resolve callback
                jQuery.post("/newPayment", data).done(function(data){
                    console.log("HEI I GOT THE PAYMENT JSON = " + data);
                    parsed_data = JSON.parse(data);
                    resolve(parsed_data['id']);
                });
            });
        },

        onAuthorize: function(data, actions) {
            console.log("JSON = " + JSON.stringify(actions.payment.getTransactions()[0]));
            console.log("TRANSACTION =  " + actions.payment.getTransactions()[0])
            console.log("PAYMENT SUCCESSFUL");
            return actions.payment.execute();
        },
        onError: function(data, actions){
            console.log("ERRORRRRRR");
            $("#warning").show();
        }

    }, '#paypal-button');
</code>```

My server side code:

```<code>app.post("/newPayment",function(req,res){
    console.log("RECEIVING POST WITH AMOUNT = " + req.body.amount);

            //CONFIGURE PAYMENY - PAYPAL PHASE 1
  var first_config = {
      'mode': 'sandbox',
      'client_id': '<MY CLIENT ID>',
      'client_secret': '<MY SECRET>'
  };

  paypal.configure(first_config);

  console.log("AMOUNT AUTHORIZED = " + req.body.amount);

  //CREATING PAYMENT
  PAYMENT = {
      "intent": "sale",
      "payer": {
          "payment_method": "paypal"
      },
      "redirect_urls": {
          "return_url": "http://return.url",
          "cancel_url": "http://cancel.url"
      },
      "transactions": [{
          "amount": {
              "currency": "EUR",
              "total": req.body.amount
          },
          "description": "This is the payment description."
      }]
  };

  //CREATING PAYMENT AND SENDING IT TO THE CLIENT
  paypal.payment.create(PAYMENT, function (error, payment) {
      if (error) {
          throw error;
      } else {
          console.log("Create Payment Response");
          res.send(JSON.stringify(payment));
      }
  });
</code>```

Now, the paypal window opens and I can insert all my data to execute a test payment.
But when I confirm payment and Paypal service should call my "onAuthorize" method, instead methon "onError" fires...

What could be the problem?
Redirect URLS?
The fact that I should execute the paypal.configure() with a .then() after it to ensure the flow of actions?

I'm really exploding trying to use Paypal services

EDIT:
Pushing my code on cloudno.de the payment is executed correctly, but running it locally it doesn't work... I don't know what to say ahah

答: actions.payment.getTransactions is not a function. You need to call actions.payment.get().then(function(result) { ... })

ContentLicense: CC BY-SA 3.0

Body:
My problem today is that I have a web application with an express checkout to execute.
I used the Client - Server architecture to avoid security issues.
So my client code is the following:

paypal.Button.render({

        env : 'sandbox',
        commit: true,
        style: {
            size: 'medium',
            color: 'gold',
            shape: 'pill',
            label: 'checkout'
        },
        locale: 'en_US',
        payment: function() {
            nickname = $("#nickname").val();
            amount = $("#amount").val();
            description = $("#description").val();
            data = {
                "nickname" : nickname,
                "amount" : amount,
                "description" : description
            };
            return new paypal.Promise(function(resolve, reject) {

                // Call your server side to get the Payment ID from step 3, then pass it to the resolve callback
                jQuery.post("/newPayment", data).done(function(data){
                    console.log("HEI I GOT THE PAYMENT JSON = " + data);
                    parsed_data = JSON.parse(data);
                    resolve(parsed_data['id']);
                });
            });
        },

        onAuthorize: function(data, actions) {
            console.log("JSON = " + JSON.stringify(actions.payment.getTransactions()[0]));
            console.log("TRANSACTION =  " + actions.payment.getTransactions()[0])
            console.log("PAYMENT SUCCESSFUL");
            return actions.payment.execute();
        },
        onError: function(data, actions){
            console.log("ERRORRRRRR");
            $("#warning").show();
        }

    }, '#paypal-button');

My server side code:

app.post("/newPayment",function(req,res){
    console.log("RECEIVING POST WITH AMOUNT = " + req.body.amount);

            //CONFIGURE PAYMENY - PAYPAL PHASE 1
  var first_config = {
      'mode': 'sandbox',
      'client_id': '<MY CLIENT ID>',
      'client_secret': '<MY SECRET>'
  };

  paypal.configure(first_config);

  console.log("AMOUNT AUTHORIZED = " + req.body.amount);

  //CREATING PAYMENT
  PAYMENT = {
      "intent": "sale",
      "payer": {
          "payment_method": "paypal"
      },
      "redirect_urls": {
          "return_url": "http://return.url",
          "cancel_url": "http://cancel.url"
      },
      "transactions": [{
          "amount": {
              "currency": "EUR",
              "total": req.body.amount
          },
          "description": "This is the payment description."
      }]
  };

  //CREATING PAYMENT AND SENDING IT TO THE CLIENT
  paypal.payment.create(PAYMENT, function (error, payment) {
      if (error) {
          throw error;
      } else {
          console.log("Create Payment Response");
          res.send(JSON.stringify(payment));
      }
  });

Now, the paypal window opens and I can insert all my data to execute a test payment.
But when I confirm payment and Paypal service should call my "onAuthorize" method, instead methon "onError" fires...

What could be the problem?
Redirect URLS?
The fact that I should execute the paypal.configure() with a .then() after it to ensure the flow of actions?

I'm really exploding trying to use Paypal services

EDIT:
Pushing my code on cloudno.de the payment is executed correctly, but running it locally it doesn't work... I don't know what to say ahah


问:
How do I make a duplicate of a folder on a remote server with asp.net and keep it speedy?
I have an ASP.NET page that needs to make a duplicate of a folder that resides on another server.   All of the file IO runs on the remote server.  This is not a question about how to copy files from one computer to another, nor is it a question about how to do a recursive directory copy.  Those tasks are pretty easy.

What I've found is that making a copy of a directory on the server running the ASP.NET application is nice and fast.  As soon as the source and destination folder reside on a remote server (i.e. a file server), it becomes incredibly slow.  I can't figure out why it's so slow, which means I can't really figure out a good way to get around the problem.  To be perfectly clear, here's an example of what I'm trying to accomplish:

The asp.net application is running on a server named "webserver"

The files are located on a server named "fileserver"

I need the website running on "webserver" to make a recursive duplicate of \\fileserver\files\setup named \\fileserver\files\setup_temp

If there are already answers to this question then please point me in the right direction.  I found loads of answers to the "how do I make a recursive copy" and "how do I copy a folder to another server"

答:
I would recommend using some remote execution commands instead of doing that from the web app itself. For e.g., using Powershell or PSExec that will not require your web app to keep a connection for the two end points of the copy operation. I am not sure how you are doing the copy but if you are calling anything in .NET to do that work, that means your server is a middle man for that operation and that will slow it down.

When I re-read your message, it looks like you are thinking the IO happens on the remote server itself. In which case, these suggestions might not be of much use. :(

ContentLicense: CC BY-SA 2.5


问:
checkbox-inline placing checkbox over text instead of beside
I'm trying to add checkboxes to my form but the bootstrap class "checkbox-inline" does not seem to be working for me.

Here is the code:

```<code><strong>Styles:</strong>
<%= f.collection_check_boxes :style_ids, Style.all, :id, :name do |cb| %>
  <% cb.label(class: "checkbox-inline input_checkbox") {cb.check_box(class: "checkbox") + cb.text} %>
<% end %>
<br><br>

<strong>Ingredients:</strong>
<%= f.collection_check_boxes :ingredient_ids, Ingredient.all, :id, :name do |cbi| %>
  <% cbi.label(class: "checkbox-inline input_checkbox") {cbi.check_box(class: "checkbox") + cbi.text} %>
<% end %>
</code>```

And here is the outcome:

Any help on this would be much appriciated, been pulling my hair out over this.

Edit: After going through the bootstrap docs, it appears checkbox-inline and radio-inline have been dropped. I just need to figure out how to get the checkboxes beside each label

Edit 2: Figured it out! in my css I had

```<code>input {
  width: 100%;
}
</code>```

I removed this and my forms broke, but my checkboxes were in the right place! So instead I just did

```<code>.input_checkbox input {
  width: auto !important;
}
</code>```

--and everything is finally fixed.

答:
Here is an example with Bootstrap 4 and two inline checkboxes. It should not be so hard to implement this structure with Ruby:

```<code><div class="form-check form-check-inline">
  <strong>Styles:</strong>

  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" id="inlineCheckbox1" value="2">Greek
  </label>
  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" id="inlineCheckbox2" value="3"> Chinese
  </label>
</div>
</code>```

https://jsfiddle.net/30c40odf/

Body:
I'm trying to add checkboxes to my form but the bootstrap class "checkbox-inline" does not seem to be working for me.

Here is the code:

Styles:
<%= f.collection_check_boxes :style_ids, Style.all, :id, :name do |cb| %>
  <% cb.label(class: "checkbox-inline input_checkbox") {cb.check_box(class: "checkbox") + cb.text} %>
<% end %>

Ingredients:
<%= f.collection_check_boxes :ingredient_ids, Ingredient.all, :id, :name do |cbi| %>
  <% cbi.label(class: "checkbox-inline input_checkbox") {cbi.check_box(class: "checkbox") + cbi.text} %>
<% end %>

And here is the outcome:

Any help on this would be much appriciated, been pulling my hair out over this.

Edit: After going through the bootstrap docs, it appears checkbox-inline and radio-inline have been dropped. I just need to figure out how to get the checkboxes beside each label

Edit 2: Figured it out! in my css I had

input {
  width: 100%;
}

I removed this and my forms broke, but my checkboxes were in the right place! So instead I just did

.input_checkbox input {
  width: auto !important;
}

--and everything is finally fixed.

Body:
Here is an example with Bootstrap 4 and two inline checkboxes. It should not be so hard to implement this structure with Ruby:

<div class="form-check form-check-inline">
  <strong>Styles:</strong>

  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" id="inlineCheckbox1" value="2">Greek
  </label>
  <label class="form-check-label">
    <input class="form-check-input" type="checkbox" id="inlineCheckbox2" value="3"> Chinese
  </label>
</div>

https://jsfiddle.net/30c40odf/


问:
Error cannot stat upon git pull
I tried to perform a git pull from a remote branch with the following command:

```<code>$ git pull origin branch_name
username@private_repository's password:
From ssh://private_repository/path/project
 * tag               branch_name       -> FETCH_HEAD
error: cannot stat 'path/name/of/file': Permission denied
error: cannot stat 'path/name/of/file': Permission denied
</code>```

But I get the following error:

```<code>error: cannot stat 'path/name/of/file': Permission denied
error: cannot stat 'path/name/of/file': Permission denied
</code>```

Does anyone know what this means and what can I do about it?

Thanks

答: Also the Angular CLI can block your files. So make sure you stop ng serve from running.</p>

Title: Error cannot stat upon git pull

Body:
I tried to perform a git pull from a remote branch with the following command:

$ git pull origin branch_name
username@private_repository's password:
From ssh://private_repository/path/project
 * tag               branch_name       -> FETCH_HEAD
error: cannot stat 'path/name/of/file': Permission denied
error: cannot stat 'path/name/of/file': Permission denied

But I get the following error:

error: cannot stat 'path/name/of/file': Permission denied
error: cannot stat 'path/name/of/file': Permission denied

Does anyone know what this means and what can I do about it?

Thanks


问:
java program is not able to read a string
```<code>import java.util.*;

class DataTypes {

    public static void main(String args[]) {
        int i = 4;
        double d= 4.0;
        String s = "Hackerrank";
        Scanner scan = new Scanner(System.in);
        int j = scan.nextInt();
        double d1 = scan.nextDouble();
        String s1 = new String();
        s1 = scan.nextLine();
        j = j+i;
        System.out.println(j);
        d1 = d1+d;
        System.out.println(d1);
        System.out.println(s+" "+s1);
        scan.close();
    }
}
</code>```

See the above code it is error free but after I input the double the program does not read the string it directly shows the output. But When I comment the scanning statements of int and double then the programs reads my string. Why is it so?

答:
You are not reading the string as you want, just use below code to make it work as you want

```<code>s1 = scan.next();
</code>```

For more information please see this link

EDIT :

If your input consist a string with spaces than you can do something like:

```<code>scan.nextLine();
s1 = scan.nextLine();
</code>```

This is because of nextDouble(), this method does not consume the last newline character of your input, and thus that newline is consumed in the next call to nextLine(). Adding newLine() before reading String will consume the new Line and you will be able to input your String.

Body:
import java.util.*;

class DataTypes {

    public static void main(String args[]) {
        int i = 4;
        double d= 4.0;
        String s = "Hackerrank";
        Scanner scan = new Scanner(System.in);
        int j = scan.nextInt();
        double d1 = scan.nextDouble();
        String s1 = new String();
        s1 = scan.nextLine();
        j = j+i;
        System.out.println(j);
        d1 = d1+d;
        System.out.println(d1);
        System.out.println(s+" "+s1);
        scan.close();
    }
}

See the above code it is error free but after I input the double the program does not read the string it directly shows the output. But When I comment the scanning statements of int and double then the programs reads my string. Why is it so?

Body:
You are not reading the string as you want, just use below code to make it work as you want

s1 = scan.next();

For more information please see this link

EDIT :

If your input consist a string with spaces than you can do something like:

scan.nextLine();
s1 = scan.nextLine();

This is because of nextDouble(), this method does not consume the last newline character of your input, and thus that newline is consumed in the next call to nextLine(). Adding newLine() before reading String will consume the new Line and you will be able to input your String.


问:
Laravel 5.5: Authorization with pivot table
I have four table users, groups, posts, and group_user. Users can follow different groups. The group_user table is for many-to-many relationship.

Every post belongs to a group and a user. I want that a user can only post a post on a group if he follows that group. I can easily check using if statement that whether a user follows that group or not. But how can I authorize the user for posting using policies.

答:
There is a complex solution for Access Control List. Read about Zizaco Entrust Library. Here you can set permissions for each route in your system. By that routing and permission you can prepare few groups.
Topic is hard but realy worth to implement:
https://github.com/Zizaco/entrust</p>


问:
Text field extension with button in ExtJs
How do I crate a special Ext.form.TextField with a button. When the user clicks on it it will show a list of of items to choose from. When something is selected it will come back to the parent form populating the form with selected item.</p>

答:
You have just perfectly described a ComboBox so you may want to look into using that instead:

http://dev.sencha.com/deploy/dev/docs/?class=Ext.form.ComboBox

If you still want a button next to a TextField, however, then you can use a CompositeField:

http://dev.sencha.com/deploy/dev/docs/?class=Ext.form.CompositeField

```<code>var MyField = new Ext.form.TextField({
    name: 'my_field',
    flex: 1
});

new Ext.form.CompositeField({
    fieldLabel: 'My field',
    items: [
        MyField,
        {
            xtype: 'button',
            text: 'Choose item'
            handler: function() {
                // Show a menu or selection dialog, then set the user's
                // selected value with:
                MyField.setValue(value);
            }
        }
    ]
});
</code>```

Body:
You have just perfectly described a ComboBox so you may want to look into using that instead:

http://dev.sencha.com/deploy/dev/docs/?class=Ext.form.ComboBox

If you still want a button next to a TextField, however, then you can use a CompositeField:

http://dev.sencha.com/deploy/dev/docs/?class=Ext.form.CompositeField

var MyField = new Ext.form.TextField({
    name: 'my_field',
    flex: 1
});

new Ext.form.CompositeField({
    fieldLabel: 'My field',
    items: [
        MyField,
        {
            xtype: 'button',
            text: 'Choose item'
            handler: function() {
                // Show a menu or selection dialog, then set the user's
                // selected value with:
                MyField.setValue(value);
            }
        }
    ]
});


问:
Render conflicts with my view in Rails
I'm starting in Ruby on Rails and I searched for in Stack Overflow and Google and I couldn't find the solution for my problem. Actually what is happening is that I have my default view application.html.erb and I limited the access to some partials verifying

What I'm trying to do is put the validates method in the model company.rb and when the user mistakes, my companies_controller.rb to render the actual action for the user fixes.

But when I do that, my validations in the application.html.erb doesn't recognises the rendered action as part of the companies_controller.rb

application.html.erb

```<code><body>
    <% if user_signed_in? %>
    <%= render 'shared/navbar' unless (controller.controller_name == "messages" && controller.action_name == "new") || (controller.controller_name == "links" && controller.action_name == "edit") || (controller.controller_name == "messages" && controller.action_name == "edit")  %>
    <%= render 'shared/sidebar' unless current_page?(root_path) || current_page?(edit_user_registration_path) || (controller.controller_name == "companies" && controller.action_name == "index") || (controller.controller_name == "companies" && controller.action_name == "new") || current_page?(new_company_path) || (controller.controller_name == "links" && controller.action_name == "edit") || (controller.controller_name == "messages" && controller.action_name == "new") || (controller.controller_name == "messages" && controller.action_name == "edit") %>
    <% end %>
    <%= yield %>
</body>
</code>```

create method from companies_controller.rb

```<code>def create
    @company = current_user.companies.new(company_params)

    respond_to do |format|
      if @company.save
        current_user.companies << @company
        format.html { redirect_to @company, notice: 'Company was successfully created.' }
        format.json { render :show, status: :created, location: @company }
      else
        format.html { render :new }
        format.json { render json: @company.errors, status: :unprocessable_entity }
      end
    end
  end
</code>```

_form.html.erb

```<code><%= form_with(model: company, local: true) do |form| %>
  <% if company.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(company.errors.count, "error") %> prohibited this company from being saved:</h2>

      <ul>
      <% company.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :name %>
    <%= form.text_field :name, id: :company_name, class: "form-control" %>
  </div>

  <div class="field">
    <%= form.label :phone %>
    <%= form.text_field :phone, id: :company_phone, class: "form-control" %>
  </div>

  <div class="field">
    <%= form.label :category %>
    <%= form.text_field :category, id: :company_category, class: "form-control" %>
  </div>

  <div class="field">
    <%= form.label :active %>
    <%= form.check_box :active %>
  </div>

  <div class="actions">
    <%= form.submit "Save", class: "btn btn-primary" %>
    <%= link_to 'Back', companies_path, class: "btn btn-default" %>
  </div>
<% end %>
</code>```

company.rb

```<code>class Company < ApplicationRecord
    validates :name, uniqueness: true, presence: true

    has_many :folders, :dependent => :destroy
    has_many :analytics, :dependent => :destroy
    has_many :leads, :dependent => :destroy
    has_many :messages, :dependent => :destroy
    has_many :links, :dependent => :destroy

    has_many :user_companies, :dependent => :destroy
    has_many :users, :through => :user_companies
end
</code>```

And the error is ActionController::UrlGenerationError in Companies#create

Can someone help with that? Sorry for my english.

Thank you!

Update December, 08.

My routes.rb

```<code>scope '/dashboard' do
    resources :companies do
      resources :users
      resources :user_companies
      resources :folder_links
      resources :folders
      resources :analytics
      resources :leads
      resources :links
      resources :messages

      get 'user_companies/new/search', to: "user_companies#search"
    end
  end
</code>```

答: @Lucas although it solved your problem, I wouldn't recommend the long unless condition you have put. I don't know why you have to check for controller action. Best way to do this is to call the render from the controller action. You can optimize this code.</p>

Title: Render conflicts with my view in Rails

Body:
I'm starting in Ruby on Rails and I searched for in Stack Overflow and Google and I couldn't find the solution for my problem. Actually what is happening is that I have my default view application.html.erb and I limited the access to some partials verifying

What I'm trying to do is put the validates method in the model company.rb and when the user mistakes, my companies_controller.rb to render the actual action for the user fixes.

But when I do that, my validations in the application.html.erb doesn't recognises the rendered action as part of the companies_controller.rb

application.html.erb

    <% if user_signed_in? %>
    <%= render 'shared/navbar' unless (controller.controller_name == "messages" && controller.action_name == "new") || (controller.controller_name == "links" && controller.action_name == "edit") || (controller.controller_name == "messages" && controller.action_name == "edit")  %>
    <%= render 'shared/sidebar' unless current_page?(root_path) || current_page?(edit_user_registration_path) || (controller.controller_name == "companies" && controller.action_name == "index") || (controller.controller_name == "companies" && controller.action_name == "new") || current_page?(new_company_path) || (controller.controller_name == "links" && controller.action_name == "edit") || (controller.controller_name == "messages" && controller.action_name == "new") || (controller.controller_name == "messages" && controller.action_name == "edit") %>
    <% end %>
    <%= yield %>

create method from companies_controller.rb

def create
    @company = current_user.companies.new(company_params)

    respond_to do |format|
      if @company.save
        current_user.companies << @company
        format.html { redirect_to @company, notice: 'Company was successfully created.' }
        format.json { render :show, status: :created, location: @company }
      else
        format.html { render :new }
        format.json { render json: @company.errors, status: :unprocessable_entity }
      end
    end
  end

_form.html.erb

<%= form_with(model: company, local: true) do |form| %>
  <% if company.errors.any? %>

<%= pluralize(company.errors.count, "error") %> prohibited this company from being saved:

      <% company.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

    <%= form.label :name %>
    <%= form.text_field :name, id: :company_name, class: "form-control" %>

    <%= form.label :phone %>
    <%= form.text_field :phone, id: :company_phone, class: "form-control" %>

    <%= form.label :category %>
    <%= form.text_field :category, id: :company_category, class: "form-control" %>

    <%= form.label :active %>
    <%= form.check_box :active %>

    <%= form.submit "Save", class: "btn btn-primary" %>
    <%= link_to 'Back', companies_path, class: "btn btn-default" %>

<% end %>

company.rb

class Company < ApplicationRecord
    validates :name, uniqueness: true, presence: true

    has_many :folders, :dependent => :destroy
    has_many :analytics, :dependent => :destroy
    has_many :leads, :dependent => :destroy
    has_many :messages, :dependent => :destroy
    has_many :links, :dependent => :destroy

    has_many :user_companies, :dependent => :destroy
    has_many :users, :through => :user_companies
end

And the error is ActionController::UrlGenerationError in Companies#create

Can someone help with that? Sorry for my english.

Thank you!

Update December, 08.

My routes.rb

scope '/dashboard' do
    resources :companies do
      resources :users
      resources :user_companies
      resources :folder_links
      resources :folders
      resources :analytics
      resources :leads
      resources :links
      resources :messages

      get 'user_companies/new/search', to: "user_companies#search"
    end
  end


问:
Auto-renewable subscription rejected for confusing reasons: Any unused portion of a free trial period, if offered, will be forfeited
My app featuring an auto-renewable subscription was rejected for the following reason, which I find very confusing.

Your app's binary did not include the following information about the
  auto-renewable nature of the subscription:

Any unused portion of a free trial period, if offered, will be
  forfeited when the user purchases a subscription to that publication,
  where applicable

This does not make any sense to me. As far as I know the free trail period will start at the moment the user purchases a subscription. It will not be forfeited at that time.

I would greatly appreciate it if anyone could clarify this.

答:
Well, I've got an answer from Apple. It solves my issue, but it's somewhat unsatisfying.

After my app was rejected for three reasons (among which the reason I described in my question) I replied by asking for a explanation.

Instead of responding with an explanation, my app is now rejected with just two reasons.


问:
How to expand and contract the height of div on click?
I want to expand and contract the height of div on click the description.I used

onclick="style='height:auto'"

This code expand the div.I want to contract it as well.

```<code><div style="height: 35px;" onclick="style='height:auto'">

      <p style="color: #9DA4AB;font-size: 15px;" >{{list.TASKDESC}}</p>

      </div>
</code>```

Current position of the page
this is the view of current page where i set the height to 35px.

After i click on div, it expands the div.

Requirement I want to contract it also on the same click on div.

答:
try like below code

```<code><div class="{{classHeight}}" (click)="onClick()">

      <p style="color: #9DA4AB;font-size: 15px;" >{{list.TASKDESC}}</p>

</div>
</code>```

make two class

```<code>.small-height{
     height: 35px;
}

.big-height{
     height:auto;
}
</code>```

when click class change

```<code>public classHeight: String = "small-height";

  onClick(){
       if(this.classHeight == 'small-height')
           this.classHeight='big-height';
       }else{
         this.classHeight='small-height';
       }
   }
</code>```

Body:
I want to expand and contract the height of div on click the description.I used

onclick="style='height:auto'"

This code expand the div.I want to contract it as well.

{{list.TASKDESC}}

Current position of the page
this is the view of current page where i set the height to 35px.

After i click on div, it expands the div.

Requirement I want to contract it also on the same click on div.

Body:
try like below code

<div class="{{classHeight}}" (click)="onClick()">

      <p style="color: #9DA4AB;font-size: 15px;" >{{list.TASKDESC}}</p>

</div>

make two class

.small-height{
     height: 35px;
}

.big-height{
     height:auto;
}

when click class change

public classHeight: String = "small-height";

  onClick(){
       if(this.classHeight == 'small-height')
           this.classHeight='big-height';
       }else{
         this.classHeight='small-height';
       }
   }


问:
How to upload image on AWS folder in CI
I have used below code

```<code>//include the S3 class
if (!class_exists('S3'))require_once('S3.php');

//AWS access info
if (!defined('awsAccessKey')) define('awsAccessKey', '****************');
if (!defined('awsSecretKey')) define('awsSecretKey', '**************************');
//instantiate the class
$s3 = new S3(awsAccessKey, awsSecretKey);

$s3->putBucket($bucket, S3::ACL_PUBLIC_READ);
</code>```

in this where we put Folder Name

答:
In S3 doesn't exist the concept of folder. What you see as folder in S3 console is just an illusion of folder.

Since each object accept / in the key, you can simulate a folder hierarchy (i.e: images/myphoto.jpg) but the filesystem is still flat.

S3 console simulate for you the folder hierarchy, but this notion is file-related, so you can't use putBucket, but putObject with a proper key:

From AWS Doc:

```<code>use Aws\S3\S3Client;

$bucket = '*** Your Bucket Name ***';
$keyname = 'images/photo.jpg';
// $filepath should be absolute path to a file on disk
$filepath = '*** Your File Path ***';

// Instantiate the client.
$s3 = S3Client::factory();

// Upload a file.
$result = $s3->putObject(array(
    'Bucket'       => $bucket,
    'Key'          => $keyname,
    'SourceFile'   => $filepath,
    'ContentType'  => 'text/plain',
    'ACL'          => 'public-read',
    'StorageClass' => 'REDUCED_REDUNDANCY',
    'Metadata'     => array(
        'param1' => 'value 1',
        'param2' => 'value 2'
    )
));

echo $result['ObjectURL'];
</code>```

Title: How to upload image on AWS folder in CI

Body:
I have used below code

//include the S3 class
if (!class_exists('S3'))require_once('S3.php');

//AWS access info
if (!defined('awsAccessKey')) define('awsAccessKey', '****************');
if (!defined('awsSecretKey')) define('awsSecretKey', '**************************');
//instantiate the class
$s3 = new S3(awsAccessKey, awsSecretKey);

$s3->putBucket($bucket, S3::ACL_PUBLIC_READ);

in this where we put Folder Name

Body:
In S3 doesn't exist the concept of folder. What you see as folder in S3 console is just an illusion of folder.

Since each object accept / in the key, you can simulate a folder hierarchy (i.e: images/myphoto.jpg) but the filesystem is still flat.

S3 console simulate for you the folder hierarchy, but this notion is file-related, so you can't use putBucket, but putObject with a proper key:

From AWS Doc:

use Aws\S3\S3Client;

$bucket = '*** Your Bucket Name ***';
$keyname = 'images/photo.jpg';
// $filepath should be absolute path to a file on disk
$filepath = '*** Your File Path ***';

// Instantiate the client.
$s3 = S3Client::factory();

// Upload a file.
$result = $s3->putObject(array(
    'Bucket'       => $bucket,
    'Key'          => $keyname,
    'SourceFile'   => $filepath,
    'ContentType'  => 'text/plain',
    'ACL'          => 'public-read',
    'StorageClass' => 'REDUCED_REDUNDANCY',
    'Metadata'     => array(
        'param1' => 'value 1',
        'param2' => 'value 2'
    )
));

echo $result['ObjectURL'];


问:
invalid 'envir' argument of type 'closure' in R shiny
I am getting "invalid 'envir' argument of type 'closure'" in the place of the plots in R shiny dashboard. Not able to figure out the error. I am trying to subset the data depending on the selection of the zipcode. It would be great if anyone could help here</p>

```<code> library(shiny)
library(shinydashboard)
library(dplyr)

varsfilter = unique(final_kings_house_data$zipcode)
vars = unique(final_kings_house_data$zipcode)

if (interactive()) {
header <- dashboardHeader(title = "Kings County Housing Data")

sidebar <- dashboardSidebar(

  sidebarSearchForm(label = "Enter a number", "searchText", "searchButton"),
  sidebarMenu(

    id = "tabs",
    menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")),
    menuItem("Widgets", icon = icon("th"), tabName = "widgets", badgeLabel = "new",
             badgeColor = "green"),
    menuItem("Charts", icon = icon("bar-chart-o"),
      menuSubItem("Trend Chart", tabName = "subitem1"),
      menuSubItem("Scatter Plot", tabName = "subitem2")),

     selectInput("filtervar", "Select zipcode", choices = vars),
     checkboxGroupInput("filteroptions", "Select zipcode", choices = varsfilter)))

body <- dashboardBody(
  tabItems(
    tabItem("subitem1", fluidRow(

      tabsetPanel(id = "tabselected",
      tabPanel("Visualization", uiOutput("Tab1")),
      tabPanel("Summary", uiOutput("Tab2"))))),

      tabItem("widgets",
      "Widgets tab content"),

      tabItem("dashboard",
      "Welcome!"),

      tabItem("subitem2",  fluidRow(

      tabsetPanel(id = "tabselected",
      tabPanel("Visualization", uiOutput("Tab3")),
      tabPanel("Summary", uiOutput("Tab4"))
    ))
    )))

shinyApp(
  ui = dashboardPage(header, sidebar, body),
 server = function(input, output,session) {

     kings_house_data = reactive({
     a = subset(final_kings_house_data, final_kings_house_data$zipcode == input$vars)
     return(a)
  })

        view_aggregate = reactive({kings_house_data() %>% group_by(view) %>% summarise(price = mean(price))})
        condition_aggregate = reactive({kings_house_data() %>% group_by(condition) %>% summarise(price = mean(price))})
        floors_aggregate = reactive({kings_house_data() %>% group_by(floors) %>% summarise(price = mean(price))})
        month_aggregate = reactive({kings_house_data() %>% group_by(month) %>% summarise(price = mean(price))})

          output$Tab1 = renderUI({

                 mainPanel(fluidRow(
                 column(6,plotOutput(outputId = "viewplot", width="300px",height="300px")),
                 column(6,plotOutput(outputId = "conditionplot", width="300px",height="300px"))),
                 fluidRow(
                 column(6,plotOutput(outputId = "floorsplot", width="300px",height="300px")),
                 column(6,plotOutput(outputId = "monthplot", width="300px",height="300px"))))

    })

           output$Tab3 = renderUI({

                 mainPanel(fluidRow(
                 column(6,plotOutput(outputId = "view_scatterplot", width="300px",height="300px")),
                 column(6,plotOutput(outputId = "condition_scatterplot", width="300px",height="300px"))),
                 fluidRow(
                 column(6,plotOutput(outputId = "floors_scatterplot", width="300px",height="300px")),
                 column(6,plotOutput(outputId = "month_scatterplot", width="300px",height="300px"))))

    })

    output$viewplot = renderPlot({ plot(price/1000 ~ view , data = view_aggregate,
                                         title = "Avg Price Vs View", xlab = "View", ylab = "Avg Price in thousands", type = "o", col = "red")})
    output$conditionplot = renderPlot({ plot(price/1000 ~ condition, data = condition_aggregate,
                                         title = "Avg Price Vs Condition", xlab = "Condition", ylab = "Avg Price in thousands", type = "o", col = "red")})
    output$floorsplot = renderPlot({ plot(price/1000 ~ floors, data = floors_aggregate,
                                         title = "Avg Price Vs No. of Floors", xlab = "No. of Floors", ylab = "Avg Price in thousands", type = "o", col = "red")})
    output$monthplot = renderPlot({ plot(price/1000 ~ month, data = month_aggregate,
                                         title = "Avg Price Vs Month", xlab = "Month", ylab = "Avg Price in thousands", type = "o", col = "red")})
    output$view_scatterplot = renderPlot({ plot(price/1000 ~ view , data = kings_house_data(),
                                         title = "Price Vs View", xlab = "View", ylab = "Price in thousands", col = "red")})
    output$condition_scatterplot = renderPlot({ plot(price/1000 ~ condition, data = kings_house_data(),
                                         title = "Price Vs Condition", xlab = "Condition", ylab = "Price in thousands", col = "red")})
    output$floors_scatterplot = renderPlot({ plot(price/1000 ~ floors, data = kings_house_data(),
                                         title = "Price Vs No. of Floors", xlab = "No. of Floors", ylab = "Price in thousands", col = "red")})
    output$month_scatterplot = renderPlot({ plot(price/1000 ~ month, data = kings_house_data(),
                                         title = "Price Vs Month", xlab = "Month", ylab = "Price in thousands", col = "red")})

  })
}
</code>```

答:
Hi this error (invalid 'envir' argument of type 'closure') means in R that you have given a function as an argument, when you really wanted the value of the function. In Shiny is this almost always that one have forgotten to add the brackets () after a reactive statment. In this case you have done it correctly for  kings_house_data but you forgotten the brackets after  view_aggregate ,condition_aggregate ,floors_aggregate and month_aggregate

Here is the corrected part of your code

```<code>output$viewplot = renderPlot({ plot(price/1000 ~ view , data = view_aggregate(),
                                    title = "Avg Price Vs View", xlab = "View", ylab = "Avg Price in thousands", type = "o", col = "red")})
output$conditionplot = renderPlot({ plot(price/1000 ~ condition, data = condition_aggregate(),
                                         title = "Avg Price Vs Condition", xlab = "Condition", ylab = "Avg Price in thousands", type = "o", col = "red")})
output$floorsplot = renderPlot({ plot(price/1000 ~ floors, data = floors_aggregate(),
                                      title = "Avg Price Vs No. of Floors", xlab = "No. of Floors", ylab = "Avg Price in thousands", type = "o", col = "red")})
output$monthplot = renderPlot({ plot(price/1000 ~ month, data = month_aggregate(),
                                     title = "Avg Price Vs Month", xlab = "Month", ylab = "Avg Price in thousands", type = "o", col = "red")})
output$view_scatterplot = renderPlot({ plot(price/1000 ~ view , data = kings_house_data(),
                                            title = "Price Vs View", xlab = "View", ylab = "Price in thousands", col = "red")})
output$condition_scatterplot = renderPlot({ plot(price/1000 ~ condition, data = kings_house_data(),
                                                 title = "Price Vs Condition", xlab = "Condition", ylab = "Price in thousands", col = "red")})
output$floors_scatterplot = renderPlot({ plot(price/1000 ~ floors, data = kings_house_data(),
                                              title = "Price Vs No. of Floors", xlab = "No. of Floors", ylab = "Price in thousands", col = "red")})
output$month_scatterplot = renderPlot({ plot(price/1000 ~ month, data = kings_house_data(),
                                             title = "Price Vs Month", xlab = "Month", ylab = "Price in thousands", col = "red")})
</code>```

Body:
I am getting "invalid 'envir' argument of type 'closure'" in the place of the plots in R shiny dashboard. Not able to figure out the error. I am trying to subset the data depending on the selection of the zipcode. It would be great if anyone could help here

 library(shiny)
library(shinydashboard)
library(dplyr)

varsfilter = unique(final_kings_house_data$zipcode)
vars = unique(final_kings_house_data$zipcode)

if (interactive()) {
header <- dashboardHeader(title = "Kings County Housing Data")

sidebar <- dashboardSidebar(

  sidebarSearchForm(label = "Enter a number", "searchText", "searchButton"),
  sidebarMenu(

    id = "tabs",
    menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")),
    menuItem("Widgets", icon = icon("th"), tabName = "widgets", badgeLabel = "new",
             badgeColor = "green"),
    menuItem("Charts", icon = icon("bar-chart-o"),
      menuSubItem("Trend Chart", tabName = "subitem1"),
      menuSubItem("Scatter Plot", tabName = "subitem2")),

     selectInput("filtervar", "Select zipcode", choices = vars),
     checkboxGroupInput("filteroptions", "Select zipcode", choices = varsfilter)))

body <- dashboardBody(
  tabItems(
    tabItem("subitem1", fluidRow(

      tabsetPanel(id = "tabselected",
      tabPanel("Visualization", uiOutput("Tab1")),
      tabPanel("Summary", uiOutput("Tab2"))))),

      tabItem("widgets",
      "Widgets tab content"),

      tabItem("dashboard",
      "Welcome!"),

      tabItem("subitem2",  fluidRow(

      tabsetPanel(id = "tabselected",
      tabPanel("Visualization", uiOutput("Tab3")),
      tabPanel("Summary", uiOutput("Tab4"))
    ))
    )))

shinyApp(
  ui = dashboardPage(header, sidebar, body),
 server = function(input, output,session) {

     kings_house_data = reactive({
     a = subset(final_kings_house_data, final_kings_house_data$zipcode == input$vars)
     return(a)
  })

        view_aggregate = reactive({kings_house_data() %>% group_by(view) %>% summarise(price = mean(price))})
        condition_aggregate = reactive({kings_house_data() %>% group_by(condition) %>% summarise(price = mean(price))})
        floors_aggregate = reactive({kings_house_data() %>% group_by(floors) %>% summarise(price = mean(price))})
        month_aggregate = reactive({kings_house_data() %>% group_by(month) %>% summarise(price = mean(price))})

          output$Tab1 = renderUI({

                 mainPanel(fluidRow(
                 column(6,plotOutput(outputId = "viewplot", width="300px",height="300px")),
                 column(6,plotOutput(outputId = "conditionplot", width="300px",height="300px"))),
                 fluidRow(
                 column(6,plotOutput(outputId = "floorsplot", width="300px",height="300px")),
                 column(6,plotOutput(outputId = "monthplot", width="300px",height="300px"))))

    })

           output$Tab3 = renderUI({

                 mainPanel(fluidRow(
                 column(6,plotOutput(outputId = "view_scatterplot", width="300px",height="300px")),
                 column(6,plotOutput(outputId = "condition_scatterplot", width="300px",height="300px"))),
                 fluidRow(
                 column(6,plotOutput(outputId = "floors_scatterplot", width="300px",height="300px")),
                 column(6,plotOutput(outputId = "month_scatterplot", width="300px",height="300px"))))

    })

    output$viewplot = renderPlot({ plot(price/1000 ~ view , data = view_aggregate,
                                         title = "Avg Price Vs View", xlab = "View", ylab = "Avg Price in thousands", type = "o", col = "red")})
    output$conditionplot = renderPlot({ plot(price/1000 ~ condition, data = condition_aggregate,
                                         title = "Avg Price Vs Condition", xlab = "Condition", ylab = "Avg Price in thousands", type = "o", col = "red")})
    output$floorsplot = renderPlot({ plot(price/1000 ~ floors, data = floors_aggregate,
                                         title = "Avg Price Vs No. of Floors", xlab = "No. of Floors", ylab = "Avg Price in thousands", type = "o", col = "red")})
    output$monthplot = renderPlot({ plot(price/1000 ~ month, data = month_aggregate,
                                         title = "Avg Price Vs Month", xlab = "Month", ylab = "Avg Price in thousands", type = "o", col = "red")})
    output$view_scatterplot = renderPlot({ plot(price/1000 ~ view , data = kings_house_data(),
                                         title = "Price Vs View", xlab = "View", ylab = "Price in thousands", col = "red")})
    output$condition_scatterplot = renderPlot({ plot(price/1000 ~ condition, data = kings_house_data(),
                                         title = "Price Vs Condition", xlab = "Condition", ylab = "Price in thousands", col = "red")})
    output$floors_scatterplot = renderPlot({ plot(price/1000 ~ floors, data = kings_house_data(),
                                         title = "Price Vs No. of Floors", xlab = "No. of Floors", ylab = "Price in thousands", col = "red")})
    output$month_scatterplot = renderPlot({ plot(price/1000 ~ month, data = kings_house_data(),
                                         title = "Price Vs Month", xlab = "Month", ylab = "Price in thousands", col = "red")})

  })
}

Body:
Hi this error (invalid 'envir' argument of type 'closure') means in R that you have given a function as an argument, when you really wanted the value of the function. In Shiny is this almost always that one have forgotten to add the brackets () after a reactive statment. In this case you have done it correctly for  kings_house_data but you forgotten the brackets after  view_aggregate ,condition_aggregate ,floors_aggregate and month_aggregate

Here is the corrected part of your code

output$viewplot = renderPlot({ plot(price/1000 ~ view , data = view_aggregate(),
                                    title = "Avg Price Vs View", xlab = "View", ylab = "Avg Price in thousands", type = "o", col = "red")})
output$conditionplot = renderPlot({ plot(price/1000 ~ condition, data = condition_aggregate(),
                                         title = "Avg Price Vs Condition", xlab = "Condition", ylab = "Avg Price in thousands", type = "o", col = "red")})
output$floorsplot = renderPlot({ plot(price/1000 ~ floors, data = floors_aggregate(),
                                      title = "Avg Price Vs No. of Floors", xlab = "No. of Floors", ylab = "Avg Price in thousands", type = "o", col = "red")})
output$monthplot = renderPlot({ plot(price/1000 ~ month, data = month_aggregate(),
                                     title = "Avg Price Vs Month", xlab = "Month", ylab = "Avg Price in thousands", type = "o", col = "red")})
output$view_scatterplot = renderPlot({ plot(price/1000 ~ view , data = kings_house_data(),
                                            title = "Price Vs View", xlab = "View", ylab = "Price in thousands", col = "red")})
output$condition_scatterplot = renderPlot({ plot(price/1000 ~ condition, data = kings_house_data(),
                                                 title = "Price Vs Condition", xlab = "Condition", ylab = "Price in thousands", col = "red")})
output$floors_scatterplot = renderPlot({ plot(price/1000 ~ floors, data = kings_house_data(),
                                              title = "Price Vs No. of Floors", xlab = "No. of Floors", ylab = "Price in thousands", col = "red")})
output$month_scatterplot = renderPlot({ plot(price/1000 ~ month, data = kings_house_data(),
                                             title = "Price Vs Month", xlab = "Month", ylab = "Price in thousands", col = "red")})


问:
Good source of Crawler / Spider IP addresses
Where could I find comprehensive list of Crawler or Spider IP address. I need IPs from google yahoo microsoft and other search engines that regularly crawl my sites.

I do not want to disable them so keep robots.txt file out of the answers. The list is for filter that is doing statistical reporting on activity on each page.

Please post links to good sources that could be used. Paid or free.

答: Your web server logs.  I believe they're free.</p>


问:
Winston logger appends "undefined" to every log entry
In a node.js / express.js - based application the winston logging framework (version 2.4.0) is used for logging. That works fine, except that undefined is appended to every log output. The type of output (string, object, ..) does not change that behaviour.
Winston is used from several .js files like this:

```<code>const logger = require('winston')
..
logger.info(`Handled request in ${Date.now() - start}ms.`);
</code>```

The output for the above log statement is:

```<code>info: Handled request in 667ms.undefined
</code>```

When logger.{info|debug|..} is replaced with a statement that logs to console the output is as expected; just the statement(s) to be logged with the 'undefined' concatenated at the end.

What might be the cause?

答:
I'm not sure what is the reason for this and I don't really have time to dig into the problem but for whatever reason the example code provided by winston creators didn't work properly for me and appended this 'undefined' after every line. Just as in your case.

I did some quick search for 'eol' in the winston module and in the console.js in Console function I printed all the options, and eol parameter. It turned out that somehow as default no eol is specified and thus this 'undefined' appendix. In fact any options that I used in winston.configure() didn't make it to the Console function. But if we create new Console explicitly and pass options to it (including eol) it works pretty well.

tl;dr;
I advise you to try this code to initialize your winston logging and modify it to suit your needs:

```<code>const winston = require('winston');
winston.configure({
  transports: [
    new winston.transports.Console({
      level: 'silly',
      eol: '\n',
      timestamp: true,
      colorize: true,
    })
  ]
});
winston.silly('testing')
</code>```

It is more of a workaround then a real solution but hey, it works, right?

EDIT:
If you are on windows you might want to try '\r\n' eol instead.

Body:
In a node.js / express.js - based application the winston logging framework (version 2.4.0) is used for logging. That works fine, except that undefined is appended to every log output. The type of output (string, object, ..) does not change that behaviour.
Winston is used from several .js files like this:

const logger = require('winston')
..
logger.info(`Handled request in ${Date.now() - start}ms.`);

The output for the above log statement is:

info: Handled request in 667ms.undefined

When logger.{info|debug|..} is replaced with a statement that logs to console the output is as expected; just the statement(s) to be logged with the 'undefined' concatenated at the end.

What might be the cause?

Body:
I'm not sure what is the reason for this and I don't really have time to dig into the problem but for whatever reason the example code provided by winston creators didn't work properly for me and appended this 'undefined' after every line. Just as in your case.

I did some quick search for 'eol' in the winston module and in the console.js in Console function I printed all the options, and eol parameter. It turned out that somehow as default no eol is specified and thus this 'undefined' appendix. In fact any options that I used in winston.configure() didn't make it to the Console function. But if we create new Console explicitly and pass options to it (including eol) it works pretty well.

tl;dr;
I advise you to try this code to initialize your winston logging and modify it to suit your needs:

const winston = require('winston');
winston.configure({
  transports: [
    new winston.transports.Console({
      level: 'silly',
      eol: '\n',
      timestamp: true,
      colorize: true,
    })
  ]
});
winston.silly('testing')

It is more of a workaround then a real solution but hey, it works, right?

EDIT:
If you are on windows you might want to try '\r\n' eol instead.


问:
Verifying ownership of AWS route 53 domain
I purchased a domain through aws route 53 being the DNS provider. Now, I would like to transfer my domain to google Firebase.

In order to do this transfer, I am being given a google-site-verification txt record to add to my DNS provider in order to verify ownership, but I don't know how to do this. The record is type: text, host: "mydomain.com", and value: "google-site-verification-etc.."

I have tried adding a record set with the google verification code as the value to my aws domain's hosted zone, but I am getting the error, The record set could not be saved because:
- The Value field contains invalid characters or is in an invalid format., because the code is not a url. What am I supposed to do here?

答:
You need to add a TXT record type, pointed to google-site-verification-etc..

P.S. The error you see depends on what record type you tried to add e.g. if A record it means the value is not an IP address, if CNAME the value is not a hostname.


问:
Code disappear sometimes from .htaccess
Hello guys i’m new and I have question. I have one website that have indexed https and http version in google search, and I added 301 redirect from HTTPS to HTTP in .htaccess. Sometimes, Randomly, 301 redirect disappeared from htaccess and I need to add it again.

This is my htaccess with 301 redirect:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code>```

And After some times, they change to this

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code>```

So the redirect was completely removed, google index again https page and I need to add it again, why? I tried many hosting company but nothing changed.

答:
Thanks @janh, so this is correct?</p>

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# BEGIN WordPress
# END WordPress
</code>```

Title: Code disappear sometimes from .htaccess

Body:
Hello guys i’m new and I have question. I have one website that have indexed https and http version in google search, and I added 301 redirect from HTTPS to HTTP in .htaccess. Sometimes, Randomly, 301 redirect disappeared from htaccess and I need to add it again.

This is my htaccess with 301 redirect:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

And After some times, they change to this

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

So the redirect was completely removed, google index again https page and I need to add it again, why? I tried many hosting company but nothing changed.

Body:
Thanks @janh, so this is correct?

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# BEGIN WordPress
# END WordPress


问:
c#- System.TypeInitializationException' error
I have a program in c# visual studio and when I try to run it it throws an error :

Exception thrown: 'System.TypeInitializationException' in SagemReader.dll

Additional information: The type initializer for 'SagemReader.SagemReaderAPI' threw an exception.

I tried looking for solution in this thread but the solutions do not work for me, so I had to post a new one.
Here is the section of my code which throws the error:

```<code>try
{
    readers = new char[-1 + 1][];

    //initailize Smart Card Reader
    Debug.WriteLine("oblSagem");
    oblSagem = SagemReaderAPI.InitSagemReader();
    //oblSagem.Initialize_Reader();
    //Test KC 20140922
    if (!booSagemReaderBusy)
    {
        booSagemReaderBusy = true;
        booCurrentSagemReaderStatusOK = oblSagem.getReaders(ref readers);
    }

    if (!booCurrentSagemReaderStatusOK)
    {
        booSagemReaderBusy = false;
        booPreviousSagemReaderStatusOK = booCurrentSagemReaderStatusOK;
    }
    else
        booSagemReaderBusy = false;

    Debug.WriteLine($"Sagem Busy : {booSagemReaderBusy} ; Current Sagem Status : {booCurrentSagemReaderStatusOK} ; Previous Sagem Status : {booPreviousSagemReaderStatusOK}" );
}
catch (Exception ex)
{
    CommonMethods.LogError("MemberInfo()", "[SEGAM ERROR]" + ex);
    booCurrentSagemReaderStatusOK = false;
    if (!booCurrentSagemReaderStatusOK)
        booPreviousSagemReaderStatusOK = booCurrentSagemReaderStatusOK;
}
</code>```

My first instinct is there is no initialization of variable for oblSagem.
as it highlights the error line:

```<code>  oblSagem = SagemReaderAPI.InitSagemReader();
</code>```

The inner exception error hightlights this:

```<code>CommonMethods.LogError("MemberInfo()", "[SEGAM ERROR]" + ex);
</code>```

With error message:

```<code>Exception thrown: 'System.NullReferenceException' in Common.dll

Additional information: Log Master must be initiate before this method. Check static constructor.
</code>```

I tried initialize it but it won't work.
Is that where I am made my mistake?

答: Catch the exception. Look at the .InnerException. It will tell you what the problem is. It will be related to the static constructor (static SagemReaderAPI() {...} or field-initializers (of static fields, like static int _someField = DoSomeStuff();) of SagemReader.SagemReaderAPI, but without that code...

Body:
I have a program in c# visual studio and when I try to run it it throws an error :

Exception thrown: 'System.TypeInitializationException' in SagemReader.dll

Additional information: The type initializer for 'SagemReader.SagemReaderAPI' threw an exception.

I tried looking for solution in this thread but the solutions do not work for me, so I had to post a new one.
Here is the section of my code which throws the error:

try
{
    readers = new char[-1 + 1][];

    //initailize Smart Card Reader
    Debug.WriteLine("oblSagem");
    oblSagem = SagemReaderAPI.InitSagemReader();
    //oblSagem.Initialize_Reader();
    //Test KC 20140922
    if (!booSagemReaderBusy)
    {
        booSagemReaderBusy = true;
        booCurrentSagemReaderStatusOK = oblSagem.getReaders(ref readers);
    }

    if (!booCurrentSagemReaderStatusOK)
    {
        booSagemReaderBusy = false;
        booPreviousSagemReaderStatusOK = booCurrentSagemReaderStatusOK;
    }
    else
        booSagemReaderBusy = false;

    Debug.WriteLine($"Sagem Busy : {booSagemReaderBusy} ; Current Sagem Status : {booCurrentSagemReaderStatusOK} ; Previous Sagem Status : {booPreviousSagemReaderStatusOK}" );
}
catch (Exception ex)
{
    CommonMethods.LogError("MemberInfo()", "[SEGAM ERROR]" + ex);
    booCurrentSagemReaderStatusOK = false;
    if (!booCurrentSagemReaderStatusOK)
        booPreviousSagemReaderStatusOK = booCurrentSagemReaderStatusOK;
}

My first instinct is there is no initialization of variable for oblSagem.
as it highlights the error line:

  oblSagem = SagemReaderAPI.InitSagemReader();

The inner exception error hightlights this:

CommonMethods.LogError("MemberInfo()", "[SEGAM ERROR]" + ex);

With error message:

Exception thrown: 'System.NullReferenceException' in Common.dll

Additional information: Log Master must be initiate before this method. Check static constructor.

I tried initialize it but it won't work.
Is that where I am made my mistake?


问:
Getting error for function call in test cases
I have a class which has all the constants used in the application

```<code>export class Constants {
    static getDefault(): any {
        return {
                url_path : '/API Path',
                etc
            }
        }
    }
</code>```

which I am consuming in service I have imported this class and using import ConstantVal = app.base.Constants;  and used in  url = 'https://'  + ConstantVal.getDefault().urlpath ;

In my Service spec.ts I am getting error

TypeError: Cannot read property 'getDefault' of undefined for the function

How to add this dependency for my test cases?

Spec code:

```<code>Spec Code:

/// <reference path='../../../../../typings/_references.ts' />

module app.base.apis {
   import ConstantVal = ptsp.base.Constants;
     describe('Service API calls tests ', function ():any {
 var apiService:any;
  var $httpBackend:any;
  //var constants:ptsp.base.Constants;
  beforeEach(angular.mock.module('App'));
  beforeEach(angular.mock.module('App.core'));
  beforeEach(angular.mock.inject(
     function ($injector:ng.auto.IInjectorService):any {
        apiService = $injector.get('apiService');
        $httpBackend = $injector.get('$httpBackend');
    }));

  it('It should call the DELETE API', function ():any {
     const constants = new Constants;
     ConstantVal.getDefault();
});
</code>```

}

答:
getDefault is defined as static method. So you need to use the full name of class in order to call this method.

```<code>Constants.getDefault();
</code>```

Another thing, you should mark your method as public method:

```<code>   export class Constants {
        public static getDefault(): any {
            return {
                    url_path : '/API Path',
                    etc
                }
            }
        }
</code>```

Spec Code:

```<code>/// <reference path='../../../../../typings/_references.ts' />

module app.base.apis {

'use strict';

import ConstantVal = ptsp.base.Constants;

declare var readJSON:any;

describe('Service API calls tests ', function ():any {

  var apiService:any;
  var $httpBackend:any;
  //var constants:ptsp.base.Constants;
  beforeEach(angular.mock.module('App'));
  beforeEach(angular.mock.module('App.core'));
  beforeEach(angular.mock.inject(
     function ($injector:ng.auto.IInjectorService):any {
        apiService = $injector.get('apiService');
        $httpBackend = $injector.get('$httpBackend');
    }));

  it('It should call the DELETE API', function ():any {
     const constants = new Constants;
     ConstantVal.getDefault();
});
}
</code>```

Body:
I have a class which has all the constants used in the application

export class Constants {
    static getDefault(): any {
        return {
                url_path : '/API Path',
                etc
            }
        }
    }

which I am consuming in service I have imported this class and using import ConstantVal = app.base.Constants;  and used in  url = 'https://'  + ConstantVal.getDefault().urlpath ;

In my Service spec.ts I am getting error

TypeError: Cannot read property 'getDefault' of undefined for the function

How to add this dependency for my test cases?

Spec code:

Spec Code:

/// <reference path='../../../../../typings/_references.ts' />

module app.base.apis {
   import ConstantVal = ptsp.base.Constants;
     describe('Service API calls tests ', function ():any {
 var apiService:any;
  var $httpBackend:any;
  //var constants:ptsp.base.Constants;
  beforeEach(angular.mock.module('App'));
  beforeEach(angular.mock.module('App.core'));
  beforeEach(angular.mock.inject(
     function ($injector:ng.auto.IInjectorService):any {
        apiService = $injector.get('apiService');
        $httpBackend = $injector.get('$httpBackend');
    }));

  it('It should call the DELETE API', function ():any {
     const constants = new Constants;
     ConstantVal.getDefault();
});

}

Body:
getDefault is defined as static method. So you need to use the full name of class in order to call this method.

Constants.getDefault();

Another thing, you should mark your method as public method:

   export class Constants {
        public static getDefault(): any {
            return {
                    url_path : '/API Path',
                    etc
                }
            }
        }

Spec Code:

/// <reference path='../../../../../typings/_references.ts' />

module app.base.apis {

'use strict';

import ConstantVal = ptsp.base.Constants;

declare var readJSON:any;

describe('Service API calls tests ', function ():any {

  var apiService:any;
  var $httpBackend:any;
  //var constants:ptsp.base.Constants;
  beforeEach(angular.mock.module('App'));
  beforeEach(angular.mock.module('App.core'));
  beforeEach(angular.mock.inject(
     function ($injector:ng.auto.IInjectorService):any {
        apiService = $injector.get('apiService');
        $httpBackend = $injector.get('$httpBackend');
    }));

  it('It should call the DELETE API', function ():any {
     const constants = new Constants;
     ConstantVal.getDefault();
});
}


答:
html:

```<code> <div *ngFor="let list of lists;let i=index" (click)="toggleList(i)" [style.height]="isListExpanded(i)?'auto':'35px'">
      <p>{{list.TASKDESC}}</p>
 </div>
</code>```

ts:

```<code>export class ClassName{

 shownList = null;

 toggleList(list) {
     if (this.isListExpanded(list)) {
         this.shownList = null;
     } else {
         this.shownList = list;
     }
  };

  isListExpanded(list) {
     return this.shownList === list;
  };
}
</code>```

Title: How to expand and contract the height of div on click?

Body:
html:

 <div *ngFor="let list of lists;let i=index" (click)="toggleList(i)" [style.height]="isListExpanded(i)?'auto':'35px'">
      <p>{{list.TASKDESC}}</p>
 </div>

ts:

export class ClassName{

 shownList = null;

 toggleList(list) {
     if (this.isListExpanded(list)) {
         this.shownList = null;
     } else {
         this.shownList = list;
     }
  };

  isListExpanded(list) {
     return this.shownList === list;
  };
}


答:
try this:</p>

```<code>import java.util.*;
class Demo{
public static void main(String args[]){
  int i = 4;
  double d= 4.0;
  String s = "Hackerrank";
  Scanner scan = new Scanner(System.in);
  int j = scan.nextInt();
  double d1 = scan.nextDouble();
  String s1  = scan.next();
  j = j+i;
  System.out.println(j);
  d1 = d1+d;
  System.out.println(d1);
  System.out.println(s+" "+s1);
  scan.close();
 }
}
</code>```

Title: java program is not able to read a string

Body:
import java.util.*;

class DataTypes {

    public static void main(String args[]) {
        int i = 4;
        double d= 4.0;
        String s = "Hackerrank";
        Scanner scan = new Scanner(System.in);
        int j = scan.nextInt();
        double d1 = scan.nextDouble();
        String s1 = new String();
        s1 = scan.nextLine();
        j = j+i;
        System.out.println(j);
        d1 = d1+d;
        System.out.println(d1);
        System.out.println(s+" "+s1);
        scan.close();
    }
}

See the above code it is error free but after I input the double the program does not read the string it directly shows the output. But When I comment the scanning statements of int and double then the programs reads my string. Why is it so?

Body:
try this:

import java.util.*;
class Demo{
public static void main(String args[]){
  int i = 4;
  double d= 4.0;
  String s = "Hackerrank";
  Scanner scan = new Scanner(System.in);
  int j = scan.nextInt();
  double d1 = scan.nextDouble();
  String s1  = scan.next();
  j = j+i;
  System.out.println(j);
  d1 = d1+d;
  System.out.println(d1);
  System.out.println(s+" "+s1);
  scan.close();
 }
}


问:
Heap versus Stack allocation implications (.NET)
From an SO answer1 about Heap and Stack, it raised me a question: Why it is important to know where the variables are allocated?

At another answer someone pointed that the stack is faster. Is this the only implication? Could someone give a code example where a simple allocation location change could solve a problem (eg. performance)?

Note that this question is .NET specific

1 the question is removed from SO.

答: I think the simplest reason is that if it is in the Heap the the garbage collection needs to deal with the variable once it is no longer needed. When on a Stack, the variable is dismissed with whatever was using it, such as a method that instantiated it.</p>

OwnerDisplayName: Vernicht

LastEditorDisplayName: Vernicht

OwnerDisplayName: David Thomas Garcia


问:
Change date format dd-MM-yyyy to yyyy-MM-dd in Java
I was trying to convert date string 08-12-2017 to 2017-12-08(LocalDate). Here is what I tried-

```<code>    String startDateString = "08-12-2017";
    LocalDate date = LocalDate.parse(startDateString);
    System.out.println(date);
</code>```

Also tried using formatter, but getting same result, an DateTimeParseException.
How can I get an output like 2017-12-08, without getting an exception?

答:
First you have to parse the string representation of your date-time into a Date object.

```<code>DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = (Date)formatter.parse("2011-11-29 12:34:25");
</code>```

Then you format the Date object back into a String in your preferred format.

```<code>DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
String mydate = dateFormat.format(date);
</code>```

Body:
I was trying to convert date string 08-12-2017 to 2017-12-08(LocalDate). Here is what I tried-

    String startDateString = "08-12-2017";
    LocalDate date = LocalDate.parse(startDateString);
    System.out.println(date);

Also tried using formatter, but getting same result, an DateTimeParseException.
How can I get an output like 2017-12-08, without getting an exception?

Body:
First you have to parse the string representation of your date-time into a Date object.

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = (Date)formatter.parse("2011-11-29 12:34:25");

Then you format the Date object back into a String in your preferred format.

DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
String mydate = dateFormat.format(date);


问:
sorting python list in recursive manner
As input I will be getting lists of lists which can up to n-levels and it will vary every time. Suppose, I have a list

```<code>[[2, 1, 3], 4, [2, 3], 7, 1, [9, [4, 2], 5]]
</code>```

here I want to sort this list and expected output is

```<code>[1, 4, [2, 3], [1, 2, 3], 7, [5, [2, 4], 9]]
</code>```

Here, first sorting is happening based of elements and then based on sum of elements inside list.

code:

```<code>input_freq = [[2,1,3],4,[2,3],7,1,[9,[4,2],5]]

res = []

def sortFreq(input_freq):
    elements = []
    list_of_elements = []

    for each in input_freq:
        if isinstance(each, list):
            print "list"
            list_of_elements.append(each)
            each.sort()
        else:
            elements.append(each)
            elements.sort()

    print elements
    print list_of_elements

sortFreq(input_freq)
</code>```

expected output:

```<code>[1, 4, [2, 3], [1, 2, 3], 7, [5, [4, 2], 9]]
</code>```

but my code returns the wrong result:

```<code>[[1, 2, 3], [2, 3], [5, 9, [4, 2]]]
</code>```

答:
Here is a solution that has the benefit of doing every sum only once. It is also quite short:</p>

```<code>import operator

def sort_lol(lol):
    srtd, sums = zip(*sorted((sort_lol(el) if isinstance(el, list) else (el, el)
                              for el in lol), key=operator.itemgetter(1)))
    return list(srtd), sum(sums)

lst = [[2,1,3],4,[2,3],7,1,[9,[4,2],5]]
print(sort_lol(lst))

# ([1, 4, [2, 3], [1, 2, 3], 7, [5, [2, 4], 9]], 43)
# note that the function returns the sorted list and the total (43 here)
</code>```

Title: sorting python list in recursive manner

Body:
As input I will be getting lists of lists which can up to n-levels and it will vary every time. Suppose, I have a list

[[2, 1, 3], 4, [2, 3], 7, 1, [9, [4, 2], 5]]

here I want to sort this list and expected output is

[1, 4, [2, 3], [1, 2, 3], 7, [5, [2, 4], 9]]

Here, first sorting is happening based of elements and then based on sum of elements inside list.

code:

input_freq = [[2,1,3],4,[2,3],7,1,[9,[4,2],5]]

res = []

def sortFreq(input_freq):
    elements = []
    list_of_elements = []

    for each in input_freq:
        if isinstance(each, list):
            print "list"
            list_of_elements.append(each)
            each.sort()
        else:
            elements.append(each)
            elements.sort()

    print elements
    print list_of_elements

sortFreq(input_freq)

expected output:

[1, 4, [2, 3], [1, 2, 3], 7, [5, [4, 2], 9]]

but my code returns the wrong result:

[[1, 2, 3], [2, 3], [5, 9, [4, 2]]]

Body:
Here is a solution that has the benefit of doing every sum only once. It is also quite short:

import operator

def sort_lol(lol):
    srtd, sums = zip(*sorted((sort_lol(el) if isinstance(el, list) else (el, el)
                              for el in lol), key=operator.itemgetter(1)))
    return list(srtd), sum(sums)

lst = [[2,1,3],4,[2,3],7,1,[9,[4,2],5]]
print(sort_lol(lst))

# ([1, 4, [2, 3], [1, 2, 3], 7, [5, [2, 4], 9]], 43)
# note that the function returns the sorted list and the total (43 here)


问:
Time conversion to IST
I'm trying to convert date & time stamp to IST using Moment. I tried following
moment(1369266934311).utcOffset("+05:30").format() I'm getting output as 2017-12-05T00:00:00+05:30.

But my required format is Tue Dec 05 2017 00:00:00 GMT+0530 (India Standard Time).

答:
Get the date object from the moment object and call its .toString() method.

```<code>moment(1369266934311).utcOffset("+05:30").toDate().toString();
// => "Thu May 23 2013 05:25:34 GMT+0530 (IST)"
</code>```

And, by the way, 1369266934311 is a different date from what you mentioned in your question.

Title: Time conversion to IST

Body:
Get the date object from the moment object and call its .toString() method.

moment(1369266934311).utcOffset("+05:30").toDate().toString();
// => "Thu May 23 2013 05:25:34 GMT+0530 (IST)"

And, by the way, 1369266934311 is a different date from what you mentioned in your question.


问:
Xcode 9.2 Upload to App Store fails with description length and invalid toolchain errors
I've read through a bunch of forums including here:

https://forums.developer.apple.com/thread/87862

and some Stack Overflow posts.

I have tried modifying my plist using the proposed solution of

```<code>find Products/ -name Info.plist -print0 | xargs -0n1 plutil -replace BuildMachineOSBuild -string 16A323
</code>```

in the archive directory that I'm trying to load, and I'm still receiving the error below. I believe I have valid Xcode and Mac OS versions. I'm running Xcode 9.2 which was released today and High Sierra 10.13.1. Why does my upload fail with these errors and how can I fix it?

The errors in text (to make this post more searchable):

The following issues occurred while distributing your application.

⚠ iTunes Store Operation Failed

   description length:2651858

⚠ iTunes Store Operation Failed

   ERROR ITMS-90534: "Invalid Toolchain. New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds."

答:
Hard Clean Product worked for me.

Hard clean the product by Command + Shift + Alt + K, then upload a new build to AppStore.

I hope this will work for you too.

Body:
I've read through a bunch of forums including here:

https://forums.developer.apple.com/thread/87862

and some Stack Overflow posts.

I have tried modifying my plist using the proposed solution of

find Products/ -name Info.plist -print0 | xargs -0n1 plutil -replace BuildMachineOSBuild -string 16A323

in the archive directory that I'm trying to load, and I'm still receiving the error below. I believe I have valid Xcode and Mac OS versions. I'm running Xcode 9.2 which was released today and High Sierra 10.13.1. Why does my upload fail with these errors and how can I fix it?

The errors in text (to make this post more searchable):

The following issues occurred while distributing your application.

⚠ iTunes Store Operation Failed

   description length:2651858

⚠ iTunes Store Operation Failed

   ERROR ITMS-90534: "Invalid Toolchain. New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds."


问:
How to end the Completion Block in Next ViewController
I am having the below block in ViewController A

```<code>dispatch_async(dispatch_get_main_queue(), ^{
    [self dismissAnimated:YES completion:^(BOOL finished) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"adjustNavBar"
                                                            object:self];
    }];
});
</code>```

After the execution of 'dismissAnimated' block method the NSNotificationCenter is getting called and the Observer in ViewController B is executing the below code

```<code>- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                            selector:@selector(adjustNavBar)
                            name:@"adjustNavBar"
                            object:nil];
}

-(void)adjustNavBar {
    [self checkForPartialScroll];
}
</code>```

after execution of the above code, it is ending in ViewController A.

But i want to end the process in ViewController B. How to do this, i am newly trying this callback functions.

using Delegates or Callbacks, can i achieve what i am trying ?

答:
try post notification before dismissviewcontroller:

```<code> [[NSNotificationCenter defaultCenter] postNotificationName:@"adjustNavBar" object:self];

dispatch_async(dispatch_get_main_queue(), ^{
    [self dismissAnimated:YES completion:^(BOOL finished) {

    }];
});
</code>```

if not work , try run checkForPartialScroll in mainthread

Body:
I am having the below block in ViewController A

dispatch_async(dispatch_get_main_queue(), ^{
    [self dismissAnimated:YES completion:^(BOOL finished) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"adjustNavBar"
                                                            object:self];
    }];
});

After the execution of 'dismissAnimated' block method the NSNotificationCenter is getting called and the Observer in ViewController B is executing the below code

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                            selector:@selector(adjustNavBar)
                            name:@"adjustNavBar"
                            object:nil];
}

-(void)adjustNavBar {
    [self checkForPartialScroll];
}

after execution of the above code, it is ending in ViewController A.

But i want to end the process in ViewController B. How to do this, i am newly trying this callback functions.

using Delegates or Callbacks, can i achieve what i am trying ?

Body:
try post notification before dismissviewcontroller:

 [[NSNotificationCenter defaultCenter] postNotificationName:@"adjustNavBar" object:self];

dispatch_async(dispatch_get_main_queue(), ^{
    [self dismissAnimated:YES completion:^(BOOL finished) {

    }];
});

if not work , try run checkForPartialScroll in mainthread


问:
using java 8 groupBy with conditions

Group by number to find groups with size bigger then 1
    2. Check if a group contains a condition (string !=null)

```<code>2a. if yes ---> remove all rows which do not have a condition (string == null)
2b. if no ---> return the group as it is (no filtering at all)
</code>```

I am trying below code but I am not able to filter the condition here. Is there any simple way to do it?

```<code>groupByList = list.stream().collect(Collectors.groupingBy(student::no));
groupByList.values().stream().map(group -> group.size() > 1)
                 .collect(Collectors.toList());
</code>```

答:
You need to use both Stream.filter(..) and Stream.map(..)

```<code>// Groups students by group number
Map<String, List<Student>> allGroups = list.stream().collect(Collectors.groupingBy(student::no));
// Filters groups that have more than 1 member
Map<String, List<Student>> filteredGroups = allGroups.entrySet().stream().filter(entry -> entry.getValue().size() > 1).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
// Removes all non-null members
Map<String, List<Student>> cleanGroups = filteredGroups.entrySet().stream()
    .map(entry -> {
        entry.setValue(entry.getValue().stream().filter(student -> student.name != null).collect(Collectors.toList()));
        return entry;
    }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
</code>```

You can pipe the execution into one big chain:

```<code>Map<String, List<Student>> cleanGroups = list.stream()
      .collect(Collectors.groupingBy(student::no))
      .entrySet().stream()
      .filter(entry -> entry.getValue().size() > 1)
      .map(entry -> {
         entry.setValue(entry.getValue().stream()
                             .filter(student -> student.name != null)
                             .collect(Collectors.toList()));
        return entry;
      })
      .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
</code>```

Please note, that you have a hidden object transformation withing the .filter(..).collect(..) above. If you need to skip that (at cost of double comparison), you can extend the lambda method to:

```<code> .map(entry -> {
     if (entry.getValue().stream.anyMatch(student.name == null)) {
        entry.setValue(entry.getValue().stream().filter(student -> student.name != null).collect(Collectors.toList()));
     }
     return entry;
 })
</code>```

Title: using java 8 groupBy with conditions

Body:
Group by number to find groups with size bigger then 1
    2. Check if a group contains a condition (string !=null)

2a. if yes ---> remove all rows which do not have a condition (string == null)
2b. if no ---> return the group as it is (no filtering at all)

I am trying below code but I am not able to filter the condition here. Is there any simple way to do it?

groupByList = list.stream().collect(Collectors.groupingBy(student::no));
groupByList.values().stream().map(group -> group.size() > 1)
                 .collect(Collectors.toList());

Body:
You need to use both Stream.filter(..) and Stream.map(..)

// Groups students by group number
Map<String, List<Student>> allGroups = list.stream().collect(Collectors.groupingBy(student::no));
// Filters groups that have more than 1 member
Map<String, List<Student>> filteredGroups = allGroups.entrySet().stream().filter(entry -> entry.getValue().size() > 1).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
// Removes all non-null members
Map<String, List<Student>> cleanGroups = filteredGroups.entrySet().stream()
    .map(entry -> {
        entry.setValue(entry.getValue().stream().filter(student -> student.name != null).collect(Collectors.toList()));
        return entry;
    }).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

You can pipe the execution into one big chain:

Map<String, List<Student>> cleanGroups = list.stream()
      .collect(Collectors.groupingBy(student::no))
      .entrySet().stream()
      .filter(entry -> entry.getValue().size() > 1)
      .map(entry -> {
         entry.setValue(entry.getValue().stream()
                             .filter(student -> student.name != null)
                             .collect(Collectors.toList()));
        return entry;
      })
      .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Please note, that you have a hidden object transformation withing the .filter(..).collect(..) above. If you need to skip that (at cost of double comparison), you can extend the lambda method to:

 .map(entry -> {
     if (entry.getValue().stream.anyMatch(student.name == null)) {
        entry.setValue(entry.getValue().stream().filter(student -> student.name != null).collect(Collectors.toList()));
     }
     return entry;
 })


问:
Decal shader not working on Device
I'm really novice and this is first time I wrote a shader for unity mobile game.
Here is the shader, working well on Editor but not on my android device :

```<code>                Shader "Decal" {
            Properties {
             _Skin("Skin (RGB)", 2D) = "white" {}
             _Dirt("Dirt (RGBA)", 2D) = "black" {}
             _Outfit("Outfit (RGBA)", 2D) = "black" {}
             _Painting("Painting (RGBA)", 2D) = "black" {}
             _Cheek("Cheek (RGBA)", 2D) = "black" {}
             _LipStick("LipStick (RGBA)", 2D) = "black" {}
             _Eye("Eye (RGBA)", 2D) = "black" {}
             _EyeLid("EyeLid (RGBA)", 2D) = "black" {}
             _ShadowHat("ShadowHat (RGBA)", 2D) = "black" {}
            }
            SubShader {
            Tags { "RenderType"="Opaque" }
            LOD 150

            CGPROGRAM
            #pragma surface surf Lambert noforwardadd

            sampler2D _Skin;
            sampler2D _Dirt;
            sampler2D _Outfit;
            sampler2D _Painting;
            sampler2D _Cheek;
            sampler2D _LipStick;
            sampler2D _Eye;
            sampler2D _EyeLid;
            sampler2D _ShadowHat;

            struct Input {
            float2 uv_Skin;
            };

            void surf (Input IN, inout SurfaceOutput o) {
            fixed4 c = tex2D(_Skin, IN.uv_Skin);
            fixed4 dirt = tex2D(_Dirt, IN.uv_Skin);
            fixed4 outfit = tex2D(_Outfit, IN.uv_Skin);
            fixed4 painting = tex2D(_Painting, IN.uv_Skin);
            fixed4 cheek = tex2D(_Cheek, IN.uv_Skin);
            fixed4 lipstick = tex2D(_LipStick, IN.uv_Skin);
            fixed4 eye = tex2D(_Eye, IN.uv_Skin);
            fixed4 eyelid = tex2D(_EyeLid, IN.uv_Skin);
            fixed4 shadowHat = tex2D(_ShadowHat, IN.uv_Skin);

            c.rgb = lerp (c.rgb, dirt.rgb, dirt.a);
            c.rgb = lerp (c.rgb, outfit.rgb, outfit.a);
            c.rgb = lerp (c.rgb, painting.rgb, painting.a);
            c.rgb = lerp (c.rgb, cheek.rgb, cheek.a);
            c.rgb = lerp (c.rgb, lipstick.rgb, lipstick.a);
            c.rgb = lerp (c.rgb, eye.rgb, eye.a);
            c.rgb = lerp (c.rgb, eyelid.rgb, eyelid.a);
            c.rgb = lerp (c.rgb, shadowHat.rgb, shadowHat.a);

            o.Albedo = c.rgb;
            o.Alpha = c.a;
            }
            ENDCG
            }

            Fallback "Mobile/VertexLit"
            }
</code>```

So any help would be very welcome :),and also one thing to clarify, I'm not sure the performance of this shader is good enough for mobile ?

Thanks you very much !

答:
So now I feel I'm doing it the wrong way. This shader is done for a character customisation and my shader skills are near to 0 so I will give up for this solution.

Finally I think it's better to merge needed texture at runtime and apply the result to a mobile shader.

Title: Decal shader not working on Device

Body:
I'm really novice and this is first time I wrote a shader for unity mobile game.
Here is the shader, working well on Editor but not on my android device :

                Shader "Decal" {
            Properties {
             _Skin("Skin (RGB)", 2D) = "white" {}
             _Dirt("Dirt (RGBA)", 2D) = "black" {}
             _Outfit("Outfit (RGBA)", 2D) = "black" {}
             _Painting("Painting (RGBA)", 2D) = "black" {}
             _Cheek("Cheek (RGBA)", 2D) = "black" {}
             _LipStick("LipStick (RGBA)", 2D) = "black" {}
             _Eye("Eye (RGBA)", 2D) = "black" {}
             _EyeLid("EyeLid (RGBA)", 2D) = "black" {}
             _ShadowHat("ShadowHat (RGBA)", 2D) = "black" {}
            }
            SubShader {
            Tags { "RenderType"="Opaque" }
            LOD 150

            CGPROGRAM
            #pragma surface surf Lambert noforwardadd

            sampler2D _Skin;
            sampler2D _Dirt;
            sampler2D _Outfit;
            sampler2D _Painting;
            sampler2D _Cheek;
            sampler2D _LipStick;
            sampler2D _Eye;
            sampler2D _EyeLid;
            sampler2D _ShadowHat;

            struct Input {
            float2 uv_Skin;
            };

            void surf (Input IN, inout SurfaceOutput o) {
            fixed4 c = tex2D(_Skin, IN.uv_Skin);
            fixed4 dirt = tex2D(_Dirt, IN.uv_Skin);
            fixed4 outfit = tex2D(_Outfit, IN.uv_Skin);
            fixed4 painting = tex2D(_Painting, IN.uv_Skin);
            fixed4 cheek = tex2D(_Cheek, IN.uv_Skin);
            fixed4 lipstick = tex2D(_LipStick, IN.uv_Skin);
            fixed4 eye = tex2D(_Eye, IN.uv_Skin);
            fixed4 eyelid = tex2D(_EyeLid, IN.uv_Skin);
            fixed4 shadowHat = tex2D(_ShadowHat, IN.uv_Skin);

            c.rgb = lerp (c.rgb, dirt.rgb, dirt.a);
            c.rgb = lerp (c.rgb, outfit.rgb, outfit.a);
            c.rgb = lerp (c.rgb, painting.rgb, painting.a);
            c.rgb = lerp (c.rgb, cheek.rgb, cheek.a);
            c.rgb = lerp (c.rgb, lipstick.rgb, lipstick.a);
            c.rgb = lerp (c.rgb, eye.rgb, eye.a);
            c.rgb = lerp (c.rgb, eyelid.rgb, eyelid.a);
            c.rgb = lerp (c.rgb, shadowHat.rgb, shadowHat.a);

            o.Albedo = c.rgb;
            o.Alpha = c.a;
            }
            ENDCG
            }

            Fallback "Mobile/VertexLit"
            }

So any help would be very welcome :),and also one thing to clarify, I'm not sure the performance of this shader is good enough for mobile ?

Thanks you very much !


问:
EPPlus Shape Lines and Connectors
I don't see functionality in EPPlus to read lines with respective connectors to other shapes.  Is this feature missing?  If so, what alternatives are there?  Can I go straight into the xml and try and determine the connectors?

I see "To" and "From" properties in the line shape but the underlying info is not much understandable to me.

Thanks for your help in advance

答:
I figured it out using XML</p>

```<code>    var drawingsXML = ws_plants.Drawings.DrawingXml;
    var connectionNodes = drawingsXML.SelectNodes("//*[local-name()='nvCxnSpPr']");

    foreach (System.Xml.XmlNode cn in connectionNodes)
    {
        var nameNode = cn.SelectNodes("*[local-name()='cNvPr']");
        string name = nameNode[0].Attributes["name"].Value;

        var connectorsNode = cn.SelectNodes("*[local-name()='cNvCxnSpPr']");

        var startConnectionNode = connectorsNode[0].SelectNodes("*[local-name()='stCxn']");
        string startId = startConnectionNode[0].Attributes["id"].Value;

        var endConnectionNode = connectorsNode[0].SelectNodes("*[local-name()='endCxn']");
        string endId = endConnectionNode[0].Attributes["id"].Value;

    }
</code>```

Title: EPPlus Shape Lines and Connectors

Body:
I figured it out using XML

    var drawingsXML = ws_plants.Drawings.DrawingXml;
    var connectionNodes = drawingsXML.SelectNodes("//*[local-name()='nvCxnSpPr']");

    foreach (System.Xml.XmlNode cn in connectionNodes)
    {
        var nameNode = cn.SelectNodes("*[local-name()='cNvPr']");
        string name = nameNode[0].Attributes["name"].Value;

        var connectorsNode = cn.SelectNodes("*[local-name()='cNvCxnSpPr']");

        var startConnectionNode = connectorsNode[0].SelectNodes("*[local-name()='stCxn']");
        string startId = startConnectionNode[0].Attributes["id"].Value;

        var endConnectionNode = connectorsNode[0].SelectNodes("*[local-name()='endCxn']");
        string endId = endConnectionNode[0].Attributes["id"].Value;

    }


问:
Link error when using lex and yacc output in Visual Studio
I am using this windows version of flex (lex) and bison (yacc) to port my query compiler from linux to Windows.
The output files, lex.yy.c, y.tab.c and y.tab.h are getting generated properly.
However, I am getting the following link error.

```<code>Error 29 error LNK2001: unresolved external symbol _yylval G:\Project\lex.yy.obj QC
Error 30 error LNK1120: 1 unresolved externals G:\Project\QC.exe QC
</code>```

I tried copying the above files generated by the original linux versions of flex and yacc to Visual studio project folder. But that too gives the same link error.

答: This looks to me like you are linking with a library for flex or bison (been a while since I used it so I can't remember exactly what you have to link with) on unix but not doing that on windows. Are you linking with the same libraries on windows?</p>

Body:
I am using this windows version of flex (lex) and bison (yacc) to port my query compiler from linux to Windows.
The output files, lex.yy.c, y.tab.c and y.tab.h are getting generated properly.
However, I am getting the following link error.

Error 29 error LNK2001: unresolved external symbol _yylval G:\Project\lex.yy.obj QC
Error 30 error LNK1120: 1 unresolved externals G:\Project\QC.exe QC

I tried copying the above files generated by the original linux versions of flex and yacc to Visual studio project folder. But that too gives the same link error.