问:
How to test react hooks with enzyme
I encountered a problem during the TDD process and the state of react hooks did not change as expected

// Header.tsx

```<code>import React, { useState, ChangeEvent, KeyboardEvent } from 'react';

interface Props {
  addUndoItem: (item: string) => void;
}

function Header(props: Props) {
  const [value, setValue] = useState('');

  const handleChange = (e: ChangeEvent<{ value: string }>) => {
    setValue(e.target.value);
  };

  const handleKeyUp = (e: KeyboardEvent) => {
    if (value && e.keyCode === 13) {
      props.addUndoItem(value);
    }
  };

  return (
    <div>
      <input
        onChange={handleChange}
        onKeyUp={handleKeyUp}
        value={value}
        data-test="input"
      />
    </div>
  );
}
</code>```

// tests/Header.tsx

```<code>it('the fn may invoked when press enter', () => {
      const userInput = 'test';
      const fn = jest.fn();
      const wrapper = shallow(<Header addUndoItem={fn} />);
      const inputEle = wrapper.find('[data-test="input"]');

      inputEle.simulate('change', {
        target: {
          value: userInput
        }
      });

      inputEle.simulate('keyUp', {
        keyCode: 13
      });
      expect(fn).toHaveBeenCalled();
      expect(fn).toHaveBeenCalledWith(userInput);
    });
</code>```

when exec simulate change, the value in Header hooks is still '' it should be test, it run successful in browser

the error is

expect(jest.fn()).toHaveBeenCalled()

```<code>Expected number of calls: >= 1
Received number of calls:    0

  48 |         keyCode: 13
  49 |       });
> 50 |       expect(fn).toHaveBeenCalled();
     |                  ^
  51 |       expect(fn).toHaveBeenCalledWith(userInput);
  52 |     });
  53 |
</code>```

答: You need to use mount instead of shallow, otherwise your input component won't be properly rendered and therefore won't be usable during the test.

Title: How to test react hooks with enzyme

Body:
I encountered a problem during the TDD process and the state of react hooks did not change as expected

// Header.tsx

import React, { useState, ChangeEvent, KeyboardEvent } from 'react';

interface Props {
  addUndoItem: (item: string) => void;
}

function Header(props: Props) {
  const [value, setValue] = useState('');

  const handleChange = (e: ChangeEvent<{ value: string }>) => {
    setValue(e.target.value);
  };

  const handleKeyUp = (e: KeyboardEvent) => {
    if (value && e.keyCode === 13) {
      props.addUndoItem(value);
    }
  };

  return (

      <input
        onChange={handleChange}
        onKeyUp={handleKeyUp}
        value={value}
        data-test="input"
      />

  );
}

// tests/Header.tsx

it('the fn may invoked when press enter', () => {
      const userInput = 'test';
      const fn = jest.fn();
      const wrapper = shallow();
      const inputEle = wrapper.find('[data-test="input"]');

      inputEle.simulate('change', {
        target: {
          value: userInput
        }
      });

      inputEle.simulate('keyUp', {
        keyCode: 13
      });
      expect(fn).toHaveBeenCalled();
      expect(fn).toHaveBeenCalledWith(userInput);
    });

when exec simulate change, the value in Header hooks is still '' it should be test, it run successful in browser

the error is

expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: >= 1
Received number of calls:    0

  48 |         keyCode: 13
  49 |       });
> 50 |       expect(fn).toHaveBeenCalled();
     |                  ^
  51 |       expect(fn).toHaveBeenCalledWith(userInput);
  52 |     });
  53 |


来源: stackexchange

问:
Facebook Video Like using custom like button
I am developing an iPhone application that lists videos posted on logged-in user's wall. I would like to provide an Like button below each video listed. When the user clicks on this Like button, the corresponding video should be liked in Facebook.

The Like button shown in the UI should match the UI theme of my app. I have gone through Facebook plug-in documentation related to Like button. Following is the link with the documentation:
http://developers.facebook.com/docs/reference/plugins/like/

But, I cannot use this Like button generated using iFrame since I will not be able to customize the look of Like button.

How can I customize my Like button? Or how can I programmatically like a Video URL? I am trying to this since long time. I have seen some iPhone apps already having custom Like button.

答: I could do it using Graph API. New SDK provides support for Graph API.</p>

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
CodeIgniter join() does not show comma separated values
I am using CodeIgniter and I am facing the problem with join method.

I want services from db_services table by service_id which is also stored in db_orders within the same column name service_id, I have service_id as a primary key in db_services table.

Now user add services by clicking the checkbox of the required services with the help of implode() function which puts the data correctly into database db_orders table under service_id column i.e. 1,2,3,5

Now when I retrieve data from db_orders I get comma-separated value from the database which works fine when I remove this line $this->db->join( $this->db->dbprefix('db_services'), $this->db->dbprefix('db_services').'.service_id = '.$this->db->dbprefix('db_orders').'.service_id' ); within my Order_model -> view_orders() function everything works like a charm but when I add that line it only show one record (first record) for instance if two (2) service_id are inserted so I get only the one which I guess the first number which is inserted during the database.

```<code><?php $services = explode(",", $value->service_id);
foreach ( $services as $service ): ?>
<a href="" class="btn btn-success btn-flat btn-xs"><?php echo $service; ?></a>
<?php endforeach; ?>
</code>```

That was the problem I have solved but the actual problem is when I use join table method it does not work let me copy-paste my code which helps you to better under the problem well I have mentioned every little details if you need more I can elaborate further.

Order_model -> view_orders()

```<code><?php
public function view_orders()
{
    $this->db->select( '*' );
    $this->db->from( $this->db->dbprefix('db_orders') );
    $this->db->join( $this->db->dbprefix('db_order_status'), $this->db->dbprefix('db_order_status').'.order_status_id = '.$this->db->dbprefix('db_orders').'.order_status_id' );
    $this->db->join( $this->db->dbprefix('db_users'), $this->db->dbprefix('db_users').'.user_id = '.$this->db->dbprefix('db_orders').'.user_id' );
    $this->db->join( $this->db->dbprefix('db_services'), $this->db->dbprefix('db_services').'.service_id = '.$this->db->dbprefix('db_orders').'.service_id' );
    $query = $this->db->get();
    return $query->result();
}
?>
</code>```

Order Controller -> index()

```<code>public function index()
{
    $data['orders'] = $this->order->view_orders();
    $data['title'] = "View All Orders";
    $this->load->template('orders/view_all_orders', $data);
}
</code>```

orders/view_all_orders.php

```<code><?php
$services = explode(",", $value->service_id);
foreach ( $services as $service ): ?>
<a href="" class="btn btn-success btn-flat btn-xs"><?php echo $service; ?></a>
<?php endforeach; ?>
</code>```

答:
Alright here is the solution I have come with.

tweaked with my function just by remove this line -> //$this->db->join( $this->db->dbprefix('db_services'), $this->db->dbprefix('db_services').'.service_id = '.$this->db->dbprefix('db_orders').'.service_id' );

```<code>public function view_orders()
{
  $this->db->select( '*' );
  $this->db->from( $this->db->dbprefix('db_orders') );
  $this->db->join( $this->db->dbprefix('db_order_status'), $this->db->dbprefix('db_order_status').'.order_status_id = '.$this->db->dbprefix('db_orders').'.order_status_id' );
  $this->db->join( $this->db->dbprefix('db_users'), $this->db->dbprefix('db_users').'.user_id = '.$this->db->dbprefix('db_orders').'.user_id' );
  //$this->db->join( $this->db->dbprefix('db_services'), $this->db->dbprefix('db_services').'.service_id = '.$this->db->dbprefix('db_orders').'.service_id' );
  $query = $this->db->get();
  return $query->result();
}
</code>```

I have created another function under Order_model -> get_services() as below.

```<code>public function get_services()
{
    $query = $this->db->get( $this->db->dbprefix('db_services') );
    return $query->result();
}
</code>```

now my controller looke like this

```<code>public function index()
{
  $data['get_services'] = $this->order->get_services(); // added this line to get all services and show it view by respective id
  $data['orders'] = $this->order->view_orders();
  $data['title'] = "View All Orders";
  $this->load->template('orders/view_all_orders', $data);
}
</code>```

and my view looks like this now.

```<code><?php foreach( $orders as $order ): ?>
  <tr>
    <td><a href="/orders/view/<?php echo $order->order_id; ?>"><?php echo $order->order_id; ?></a></td>
    <td><?php echo $order->status; ?></td>
    <td>
      <a href="/user/view/<?php echo $order->user_id; ?>"><?php echo $order->name;?></a>
    </td>
    <td>
      <?php
        $service_ids = explode(',', $order->service_id);
        foreach ($service_ids as $service_id) {
          foreach ($get_services as $row) {
            if ($service_id == $row->service_id) {
              echo $row->service_name;
            }
          }
        }
      ?>
    </td>
    <td><?php echo gmdate('l jS F, Y',$order->created); ?></td>
    <td>
      <a class="btn btn-xs btn-flat btn-info" href="/orders/view/<?php echo $order->order_id; ?>"><i class="fas fa-eye"></i></a>
      <a class="btn btn-xs btn-flat btn-success" href="/orders/edit/<?php echo $order->order_id; ?>"><i class="fas fa-edit"></i></a>
      <a class="btn btn-xs btn-flat btn-danger" href="/orders/delete/<?php echo $order->order_id; ?>"><i class="fas fa-trash"></i></a>
    </td>
  </tr>
<?php endforeach; ?>
</code>```

As far as this helped me solve my problem but I am still confused am I following the right direction

Body:
I am using CodeIgniter and I am facing the problem with join method.

I want services from db_services table by service_id which is also stored in db_orders within the same column name service_id, I have service_id as a primary key in db_services table.

Now user add services by clicking the checkbox of the required services with the help of implode() function which puts the data correctly into database db_orders table under service_id column i.e. 1,2,3,5

Now when I retrieve data from db_orders I get comma-separated value from the database which works fine when I remove this line $this->db->join( $this->db->dbprefix('db_services'), $this->db->dbprefix('db_services').'.service_id = '.$this->db->dbprefix('db_orders').'.service_id' ); within my Order_model -> view_orders() function everything works like a charm but when I add that line it only show one record (first record) for instance if two (2) service_id are inserted so I get only the one which I guess the first number which is inserted during the database.

<?php $services = explode(",", $value->service_id);
foreach ( $services as $service ): ?>
<?php echo $service; ?>
<?php endforeach; ?>

That was the problem I have solved but the actual problem is when I use join table method it does not work let me copy-paste my code which helps you to better under the problem well I have mentioned every little details if you need more I can elaborate further.

Order_model -> view_orders()

<?php
public function view_orders()
{
    $this->db->select( '*' );
    $this->db->from( $this->db->dbprefix('db_orders') );
    $this->db->join( $this->db->dbprefix('db_order_status'), $this->db->dbprefix('db_order_status').'.order_status_id = '.$this->db->dbprefix('db_orders').'.order_status_id' );
    $this->db->join( $this->db->dbprefix('db_users'), $this->db->dbprefix('db_users').'.user_id = '.$this->db->dbprefix('db_orders').'.user_id' );
    $this->db->join( $this->db->dbprefix('db_services'), $this->db->dbprefix('db_services').'.service_id = '.$this->db->dbprefix('db_orders').'.service_id' );
    $query = $this->db->get();
    return $query->result();
}
?>

Order Controller -> index()

public function index()
{
    $data['orders'] = $this->order->view_orders();
    $data['title'] = "View All Orders";
    $this->load->template('orders/view_all_orders', $data);
}

orders/view_all_orders.php

<?php
$services = explode(",", $value->service_id);
foreach ( $services as $service ): ?>
<?php echo $service; ?>
<?php endforeach; ?>

Body:
Alright here is the solution I have come with.

tweaked with my function just by remove this line -> //$this->db->join( $this->db->dbprefix('db_services'), $this->db->dbprefix('db_services').'.service_id = '.$this->db->dbprefix('db_orders').'.service_id' );

public function view_orders()
{
  $this->db->select( '*' );
  $this->db->from( $this->db->dbprefix('db_orders') );
  $this->db->join( $this->db->dbprefix('db_order_status'), $this->db->dbprefix('db_order_status').'.order_status_id = '.$this->db->dbprefix('db_orders').'.order_status_id' );
  $this->db->join( $this->db->dbprefix('db_users'), $this->db->dbprefix('db_users').'.user_id = '.$this->db->dbprefix('db_orders').'.user_id' );
  //$this->db->join( $this->db->dbprefix('db_services'), $this->db->dbprefix('db_services').'.service_id = '.$this->db->dbprefix('db_orders').'.service_id' );
  $query = $this->db->get();
  return $query->result();
}

I have created another function under Order_model -> get_services() as below.

public function get_services()
{
    $query = $this->db->get( $this->db->dbprefix('db_services') );
    return $query->result();
}

now my controller looke like this

public function index()
{
  $data['get_services'] = $this->order->get_services(); // added this line to get all services and show it view by respective id
  $data['orders'] = $this->order->view_orders();
  $data['title'] = "View All Orders";
  $this->load->template('orders/view_all_orders', $data);
}

and my view looks like this now.

<?php foreach( $orders as $order ): ?>
  <tr>
    <td><a href="/orders/view/<?php echo $order->order_id; ?>"><?php echo $order->order_id; ?></a></td>
    <td><?php echo $order->status; ?></td>
    <td>
      <a href="/user/view/<?php echo $order->user_id; ?>"><?php echo $order->name;?></a>
    </td>
    <td>
      <?php
        $service_ids = explode(',', $order->service_id);
        foreach ($service_ids as $service_id) {
          foreach ($get_services as $row) {
            if ($service_id == $row->service_id) {
              echo $row->service_name;
            }
          }
        }
      ?>
    </td>
    <td><?php echo gmdate('l jS F, Y',$order->created); ?></td>
    <td>
      <a class="btn btn-xs btn-flat btn-info" href="/orders/view/<?php echo $order->order_id; ?>"><i class="fas fa-eye"></i></a>
      <a class="btn btn-xs btn-flat btn-success" href="/orders/edit/<?php echo $order->order_id; ?>"><i class="fas fa-edit"></i></a>
      <a class="btn btn-xs btn-flat btn-danger" href="/orders/delete/<?php echo $order->order_id; ?>"><i class="fas fa-trash"></i></a>
    </td>
  </tr>
<?php endforeach; ?>

As far as this helped me solve my problem but I am still confused am I following the right direction


问:
Why do I have problems with Ext JS 6.2.0?
I'm trying to create a simple app un Netbeans with Ext JS 6.2.0.

In the ui.js file I just creat a toolbar and a form.

var toolbar = Ext.create('Ext.toolbar.Toolbar', {
    renderTo: document.body,
    width   : 400,
    margin  : '5 0 0 0',
    items   : [{
        xtype: 'datefield',
        anchor: '100%',
        format: 'W-Y',
        fieldLabel: 'From',
        name: 'from_date',
        maxValue: new Date()  // limited to the current date or prior
    }]
});

Ext.create('Ext.form.Panel', {
    renderTo: document.body,
    title: 'User Form',
    height: 300,
    width: 585,
    defaults: {
        xtype: 'textfield',
        labelAlign: 'top',
        padding: 10
    },
    layout: 'hbox',
    items: [toolbar]
});
```

<p>Then in the index.jsp I call this file and the other files such as theme-classic-all-debug.css, theme-classic-debug.js and ext-all-debug.js.</p>

<p>I incorprate this with these tags:</p>

<pre class="lang-html prettyprint-override"><code><script src="WEB-INF/ext-6.2.0/build/ext-all-debug.js" type="text/javascript"></script>

<link href="WEB-INF/ext-6.2.0/build/classic/theme-classic/resources/theme-classic-all-debug.css" rel="stylesheet" type="text/css"/>
</code>```

But the problem is that when I'm trying to run the application, in the console of the browser, I see these errors and the page doesn't show anything.

The errors:

---SPANISH---

```<code>El script de “http://localhost:8080/pruebaMCC/WEB-INF/ext-6.2.0/build/ext-all-debug.js” fue cargado a pesar de que su tipo MIME (“text/html”) no es un tipo MIME válido de JavaScript.

Ha fallado la carga del <script> con origen "http://localhost:8080/pruebaMCC/WEB-INF/ext-6.2.0/build/ext-all-debug.js".
</code>```

---ENGLISH---

```<code>
<script> loading with source "http: // localhost: 8080 / test MCC / WEB-INF / ext-6.2.0 / build / ext-all-debug.js" failed.
</code>```

I don't know how can I resolve it.

Please help me.

Thanks,
Sofy

答:
Most likely the problem is that there are no static resources. To access resources from the jsp template, it is not enough to indicate the path to the resources on your computer. Afterwards the java code will be compiled and build and your resources will be packed into a jar or war with which the server will then work. And the final path depends on the context to which deploy jar.

Try

```<code><script src="<%=request.getContextPath()%>/ext-6.2.0/build/ext-all-debug.js" type="text/javascript"></script>

<link href="<%=request.getContextPath()%>/ext-6.2.0/build/classic/theme-classic/resources/theme-classic-all-debug.css" rel="stylesheet" type="text/css"/>
</code>```

It may not help. It all depends at your settings in java project.

Body:
I'm trying to create a simple app un Netbeans with Ext JS 6.2.0.

In the ui.js file I just creat a toolbar and a form.

var toolbar = Ext.create('Ext.toolbar.Toolbar', {
    renderTo: document.body,
    width   : 400,
    margin  : '5 0 0 0',
    items   : [{
        xtype: 'datefield',
        anchor: '100%',
        format: 'W-Y',
        fieldLabel: 'From',
        name: 'from_date',
        maxValue: new Date()  // limited to the current date or prior
    }]
});

Ext.create('Ext.form.Panel', {
    renderTo: document.body,
    title: 'User Form',
    height: 300,
    width: 585,
    defaults: {
        xtype: 'textfield',
        labelAlign: 'top',
        padding: 10
    },
    layout: 'hbox',
    items: [toolbar]
});

Then in the index.jsp I call this file and the other files such as theme-classic-all-debug.css, theme-classic-debug.js and ext-all-debug.js.

I incorprate this with these tags:

<link href="WEB-INF/ext-6.2.0/build/classic/theme-classic/resources/theme-classic-all-debug.css" rel="stylesheet" type="text/css"/>

But the problem is that when I'm trying to run the application, in the console of the browser, I see these errors and the page doesn't show anything.

The errors:

---SPANISH---

El script de “http://localhost:8080/pruebaMCC/WEB-INF/ext-6.2.0/build/ext-all-debug.js” fue cargado a pesar de que su tipo MIME (“text/html”) no es un tipo MIME válido de JavaScript.

Ha fallado la carga del

Body:
Most likely the problem is that there are no static resources. To access resources from the jsp template, it is not enough to indicate the path to the resources on your computer. Afterwards the java code will be compiled and build and your resources will be packed into a jar or war with which the server will then work. And the final path depends on the context to which deploy jar.

Try

<script src="<%=request.getContextPath()%>/ext-6.2.0/build/ext-all-debug.js" type="text/javascript"></script>

<link href="<%=request.getContextPath()%>/ext-6.2.0/build/classic/theme-classic/resources/theme-classic-all-debug.css" rel="stylesheet" type="text/css"/>

It may not help. It all depends at your settings in java project.


问:
Reducing Function Complexity
I'm writing a simple calculator in React. I'm trying to update the state of a component based on which button is clicked (as you would expect). The component's state is as follows:

```<code>this.state = {
  total: null,
  next: null,
  operation: null,
}

</code>```

Presently, I have one long if/else statement that checks a bunch of scenarios to determine what the appropriate values should be. I'm wondering how I could rewrite this to reduce the complexity of the function:

```<code>handleClick(buttonName) {
    let { total, next } = this.state;
    const { operation } = this.state;
    let obj;
    const nums = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    const syms = ['+', '-', 'X', '/', '%'];
    const equal = '=';
    const reset = 'AC';
    const decimalPoint = '.';

    if (total === null && nums.indexOf(buttonName) >= 0) {
      this.setState({
        total: buttonName,
      });
    } else if (total !== null
      && buttonName === decimalPoint
      && (total.indexOf(decimalPoint) === -1)) {
      this.setState({
        total: total += buttonName,
      });
    } else if (total !== null
      && next !== null
      && buttonName === decimalPoint
      && (next.indexOf(decimalPoint) === -1)) {
      this.setState({
        next: next += buttonName,
      });
    } else if (total !== null
      && operation === null
      && syms.indexOf(buttonName) >= 0) {
      this.setState({
        operation: buttonName,
      });
    } else if (total !== null
      && operation === null
      && nums.indexOf(buttonName) >= 0) {
      this.setState({
        total: total += buttonName,
      });
    } else if (total !== null
      && operation !== null
      && next === null
      && nums.indexOf(buttonName) >= 0) {
      this.setState({
        next: buttonName,
      });
    } else if (total !== null
      && operation !== null
      && next !== null
      && nums.indexOf(buttonName) >= 0) {
      this.setState({
        next: next += buttonName,
      });
    } else if (total !== null
      && operation !== null
      && next !== null
      && ((buttonName === equal) || (buttonName === reset))) {
      obj = method.calculate(this.state, operation);
      this.setState({
        total: obj.total,
        next: obj.next,
        operation: buttonName,
      });
    }
  }
</code>```

PS. the "method.calculate" function is stated in another module.

答:
In short:

Try to store your conditions values in variables (please try to give them better names)

```<code>   const check1 = nums.indexOf(buttonName) >= 0
   const check2 = buttonName === decimalPoint
   const check3 = next.indexOf(decimalPoint) === -1)
</code>```

Then, try to reconstruct your statements as nested, using the variables instead of expressions. For instance:

```<code>    if (total) {
     if (check2 && check3) {
        if (next) {
           this.setState({ next: next += buttonName });
        }
        else {
           this.setState({total: total += buttonName });
        }
     }
     else {
     }
    }
</code>```

This is of-course just a proposal. In your case it will:

Stop re-calculating expressions over and over again

Make code more readable and maintainable

Allow you to collaborate with other developers

And yes.. Stack Exchange Code review is a thing :)

Title: Reducing Function Complexity

Body:
I'm writing a simple calculator in React. I'm trying to update the state of a component based on which button is clicked (as you would expect). The component's state is as follows:

this.state = {
  total: null,
  next: null,
  operation: null,
}

Presently, I have one long if/else statement that checks a bunch of scenarios to determine what the appropriate values should be. I'm wondering how I could rewrite this to reduce the complexity of the function:

handleClick(buttonName) {
    let { total, next } = this.state;
    const { operation } = this.state;
    let obj;
    const nums = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    const syms = ['+', '-', 'X', '/', '%'];
    const equal = '=';
    const reset = 'AC';
    const decimalPoint = '.';

    if (total === null && nums.indexOf(buttonName) >= 0) {
      this.setState({
        total: buttonName,
      });
    } else if (total !== null
      && buttonName === decimalPoint
      && (total.indexOf(decimalPoint) === -1)) {
      this.setState({
        total: total += buttonName,
      });
    } else if (total !== null
      && next !== null
      && buttonName === decimalPoint
      && (next.indexOf(decimalPoint) === -1)) {
      this.setState({
        next: next += buttonName,
      });
    } else if (total !== null
      && operation === null
      && syms.indexOf(buttonName) >= 0) {
      this.setState({
        operation: buttonName,
      });
    } else if (total !== null
      && operation === null
      && nums.indexOf(buttonName) >= 0) {
      this.setState({
        total: total += buttonName,
      });
    } else if (total !== null
      && operation !== null
      && next === null
      && nums.indexOf(buttonName) >= 0) {
      this.setState({
        next: buttonName,
      });
    } else if (total !== null
      && operation !== null
      && next !== null
      && nums.indexOf(buttonName) >= 0) {
      this.setState({
        next: next += buttonName,
      });
    } else if (total !== null
      && operation !== null
      && next !== null
      && ((buttonName === equal) || (buttonName === reset))) {
      obj = method.calculate(this.state, operation);
      this.setState({
        total: obj.total,
        next: obj.next,
        operation: buttonName,
      });
    }
  }

PS. the "method.calculate" function is stated in another module.

Body:
In short:

Try to store your conditions values in variables (please try to give them better names)

   const check1 = nums.indexOf(buttonName) >= 0
   const check2 = buttonName === decimalPoint
   const check3 = next.indexOf(decimalPoint) === -1)

Then, try to reconstruct your statements as nested, using the variables instead of expressions. For instance:

    if (total) {
     if (check2 && check3) {
        if (next) {
           this.setState({ next: next += buttonName });
        }
        else {
           this.setState({total: total += buttonName });
        }
     }
     else {
     }
    }

This is of-course just a proposal. In your case it will:

Stop re-calculating expressions over and over again

Make code more readable and maintainable

Allow you to collaborate with other developers

And yes.. Stack Exchange Code review is a thing :)


问:
How to pull and loop the data in R studio?
It would be great if some one could help on below requirement.

My requirement is pull the data from Hive table based on "Fiscal Quarter" and load it to txt file. Process should be like loop, i would expect 3 txt files (FY19Q1_Txtfile1.txt/FY19Q2_Txtfile2.txt/FY19Q3_Txtfile3.txt) with 3 iterations.

答:
Once your table is stored as a data.frame on R, named data for example, you can do that :

```<code>write.csv(data[data$Fiscal_Quarter == 'FY19Q1'], 'FY19Q1_Txtfile1.txt')
write.csv(data[data$Fiscal_Quarter == 'FY19Q2'], 'FY19Q2_Txtfile3.txt')
write.csv(data[data$Fiscal_Quarter == 'FY19Q3'], 'FY19Q3_Txtfile3.txt')
</code>```

And if you want to use a loop instead :

```<code>for (i in 1:3){
    file_name = paste('FY19Q', i, '_Txtfile', i, '.txt',sep="")
    FQ = paste('FY19Q', i, sep="")
    write.csv(data[data$Fiscal_Quarter == FQ], file_name)
}
</code>```

I hope this answers the question.

Body:
Once your table is stored as a data.frame on R, named data for example, you can do that :

write.csv(data[data$Fiscal_Quarter == 'FY19Q1'], 'FY19Q1_Txtfile1.txt')
write.csv(data[data$Fiscal_Quarter == 'FY19Q2'], 'FY19Q2_Txtfile3.txt')
write.csv(data[data$Fiscal_Quarter == 'FY19Q3'], 'FY19Q3_Txtfile3.txt')

And if you want to use a loop instead :

for (i in 1:3){
    file_name = paste('FY19Q', i, '_Txtfile', i, '.txt',sep="")
    FQ = paste('FY19Q', i, sep="")
    write.csv(data[data$Fiscal_Quarter == FQ], file_name)
}

I hope this answers the question.


问:
Create a temp table show percentage of null value for all column in a given table
I have an sql server loop exercise : Write code to create a table that shows percentage of null/ blank value for all the columns of table sql_practice . ( sql_practice table of my database have many columns so I need to use loop but I dont know how to code)</p>

答:
Not really sure what you are trying to accomplish but something like this will give you the percentage of rows for a single column that is not null. You could extend this to additional columns easily.</p>

```<code>declare @Something table
(
    MyCol int null
)

insert @Something values
(0),(1),(2),(3),(4),(5),(null),(null)

select NotNullPercentage = count(MyCol) / (count(*) * 1.0) --need to multiply by 1.0 to avoid integer math
from @Something
</code>```

Body:
Not really sure what you are trying to accomplish but something like this will give you the percentage of rows for a single column that is not null. You could extend this to additional columns easily.

declare @Something table
(
    MyCol int null
)

insert @Something values
(0),(1),(2),(3),(4),(5),(null),(null)

select NotNullPercentage = count(MyCol) / (count(*) * 1.0) --need to multiply by 1.0 to avoid integer math
from @Something


问:
Missing typeface when activating wordpress Divi child theme
after creating a child theme that is functioning correctly, I have a problem with the typeface modules.ttf font-family : ETmodules
The typeface works correctly if I don't use the child theme and it is not considered missing when I verify in development tools. You can see the problem in the header on this page before the telephone number: https://preprod03.groupepointsrezo.fr/
I tried adding the typeface to the child them using the same folder hierarchy.
I have also added this to my child theme style.css file.

```<code>@font-face {
font-family: ETmodules;
src: url(core/admin/fonts/modules.ttf);
}
</code>```

Thanks for any and all help.

答:
@stender answer is correct. I am missing the backslash in the style content

```<code>content: "\e090";
</code>```

Thank you. I don't know how to attribute the answer to you because you answered with a comment

Body:
after creating a child theme that is functioning correctly, I have a problem with the typeface modules.ttf font-family : ETmodules
The typeface works correctly if I don't use the child theme and it is not considered missing when I verify in development tools. You can see the problem in the header on this page before the telephone number: https://preprod03.groupepointsrezo.fr/
I tried adding the typeface to the child them using the same folder hierarchy.
I have also added this to my child theme style.css file.

@font-face {
font-family: ETmodules;
src: url(core/admin/fonts/modules.ttf);
}

Thanks for any and all help.

Body:
@stender answer is correct. I am missing the backslash in the style content

content: "\e090";

Thank you. I don't know how to attribute the answer to you because you answered with a comment


问:
In operator returns false
Why this statement returns false? It's really weird</p>

```<code>console.log("100038916831294" in ["100003748210938", "100038916831294"]);
</code>```

答:
The in operator tells you whether a value exists as a property name in an object. The property names of your array are "0" and "1".

You can use one of the Array methods to check if a value is in the array, like .indexOf() or .includes():

```<code>console.log(["100003748210938", "100038916831294"].includes("100038916831294"));
</code>```

Title: In operator returns false

Body:
Why this statement returns false? It's really weird

console.log("100038916831294" in ["100003748210938", "100038916831294"]);

Body:
The in operator tells you whether a value exists as a property name in an object. The property names of your array are "0" and "1".

You can use one of the Array methods to check if a value is in the array, like .indexOf() or .includes():

console.log(["100003748210938", "100038916831294"].includes("100038916831294"));


问:
Using reflection with generic types and implicit conversions
I'm trying to use reflection to set properties on some OpenXML types (e.g. Justification).  Assigning a value by enumerating all possibilities is straight-forward:

```<code>// attr is an XmlAttribute, so .Name and .Value are Strings
if (attr.Name == "Val")
{
    if (element is Justification)
    {
        ((Justification)element).Val = (JustificationValues)Enum.Parse(typeof(JustificationValues), attr.Value);
            return;
    }
    else
    {
        // test for dozens of other types, such as TabStop
    }
}
</code>```

What makes this difficult to do via reflection is:
1) The type of the Val property is EnumValue<T>, so I don't know how to extract the type to pass as the first argument to Enum.Parse.
2) There is an implicit conversion from the actual enumeration type to the EnumValue<> type, which I don't know how to invoke with reflection.

I would like the code to end up looking something like:

```<code>PropertyInfo pInfo = element.GetType().GetProperty(attr.Name);
Object value = ConvertToPropType(pInfo.PropertyType, attr.Value); /* this
    would return an instance of EnumValue<JustificationValues> in this case */
pInfo.SetValue(element, value, null);
</code>```

How do I implement ConvertToPropType?  Or is there a better solution?

Thanks

Edit:
I got a solution working using Earwicker's suggestion, but it relies on the convenient fact that the enumeration's type name can be derived from the node's type name ("Justification" -> "JustificationValues").  I'm still curious how to solve this in the general case, though.

Edit2:
GetGenericArguments got me the rest of the way there.  Thanks.

答:
This might only work with basic types but it was good enough for what I'm doing</p>

```<code>PropertyInfo pInfo = element.GetType().GetProperty(attr.Name);
Object value = System.Convert.ChangeType(attr.Value, pInfo.PropertyType);
pInfo.SetValue(element, value, null);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to use reflection to set properties on some OpenXML types (e.g. Justification).  Assigning a value by enumerating all possibilities is straight-forward:

// attr is an XmlAttribute, so .Name and .Value are Strings
if (attr.Name == "Val")
{
    if (element is Justification)
    {
        ((Justification)element).Val = (JustificationValues)Enum.Parse(typeof(JustificationValues), attr.Value);
            return;
    }
    else
    {
        // test for dozens of other types, such as TabStop
    }
}

What makes this difficult to do via reflection is:
1) The type of the Val property is EnumValue<T>, so I don't know how to extract the type to pass as the first argument to Enum.Parse.
2) There is an implicit conversion from the actual enumeration type to the EnumValue<> type, which I don't know how to invoke with reflection.

I would like the code to end up looking something like:

PropertyInfo pInfo = element.GetType().GetProperty(attr.Name);
Object value = ConvertToPropType(pInfo.PropertyType, attr.Value); /* this
    would return an instance of EnumValue<JustificationValues> in this case */
pInfo.SetValue(element, value, null);

How do I implement ConvertToPropType?  Or is there a better solution?

Thanks

Edit:
I got a solution working using Earwicker's suggestion, but it relies on the convenient fact that the enumeration's type name can be derived from the node's type name ("Justification" -> "JustificationValues").  I'm still curious how to solve this in the general case, though.

Edit2:
GetGenericArguments got me the rest of the way there.  Thanks.

Body:
This might only work with basic types but it was good enough for what I'm doing

PropertyInfo pInfo = element.GetType().GetProperty(attr.Name);
Object value = System.Convert.ChangeType(attr.Value, pInfo.PropertyType);
pInfo.SetValue(element, value, null);


问:
crash app when upload the image from gallery to firebase storage
when the app is crashing , it says :

```<code>"java.lang.NoSuchMethodError: No virtual method getToken(Z)Lcom/google/android/gms/tasks/Task; in class Lcom/google/firebase/FirebaseApp; or its super classes (declaration of 'com.google.firebase.FirebaseApp' appears in /data/app/com.example.minisign-uZwwNJVtsjlOVpgpqIRyHQ==/base.apk)at com.google.firebase.storage.internal.Util.getCurrentAuthToken(com.google.firebase:firebase-storage@@16.0.4:148)"
</code>```

I have tried many things but didn't solve it .
My code :

```<code>final StorageReference fileReference=storageReference.child(imageuri.getLastPathSegment()+"."+getfileExtension(imageuri));
            uploadTask=fileReference.putFile(imageuri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    // Get a URL to the uploaded content
                    //Uri downloadUrl = taskSnapshot.getUploadSessionUri();
                    //pd.dismiss();
                    Toast.makeText(SettingsActivity.this, "Image Uploaded!!", Toast.LENGTH_SHORT).show();
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    Toast.makeText(SettingsActivity.this,"Failed!",Toast.LENGTH_SHORT).show();
                    //pd.dismiss();
                }
            });
           }
</code>```

and for my gradle :

```<code>{implementation 'com.google.firebase:firebase-analytics:17.2.2'
implementation 'com.google.firebase:firebase-storage:16.0.4'

implementation 'com.firebaseui:firebase-ui-database:1.2.0'

implementation 'com.google.firebase:firebase-auth:19.2.0'

implementation 'com.google.firebase:firebase-database:19.2.0'}
</code>```

答:
Try to add the firebase sdk library in the build.gradle file.</p>

```<code>implementation 'com.google.firebase:firebase-core:17.0.0'
</code>```

Body:
when the app is crashing , it says :

"java.lang.NoSuchMethodError: No virtual method getToken(Z)Lcom/google/android/gms/tasks/Task; in class Lcom/google/firebase/FirebaseApp; or its super classes (declaration of 'com.google.firebase.FirebaseApp' appears in /data/app/com.example.minisign-uZwwNJVtsjlOVpgpqIRyHQ==/base.apk)at com.google.firebase.storage.internal.Util.getCurrentAuthToken(com.google.firebase:firebase-storage@@16.0.4:148)"

I have tried many things but didn't solve it .
My code :

final StorageReference fileReference=storageReference.child(imageuri.getLastPathSegment()+"."+getfileExtension(imageuri));
            uploadTask=fileReference.putFile(imageuri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    // Get a URL to the uploaded content
                    //Uri downloadUrl = taskSnapshot.getUploadSessionUri();
                    //pd.dismiss();
                    Toast.makeText(SettingsActivity.this, "Image Uploaded!!", Toast.LENGTH_SHORT).show();
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    Toast.makeText(SettingsActivity.this,"Failed!",Toast.LENGTH_SHORT).show();
                    //pd.dismiss();
                }
            });
           }

and for my gradle :

{implementation 'com.google.firebase:firebase-analytics:17.2.2'
implementation 'com.google.firebase:firebase-storage:16.0.4'

implementation 'com.firebaseui:firebase-ui-database:1.2.0'

implementation 'com.google.firebase:firebase-auth:19.2.0'

implementation 'com.google.firebase:firebase-database:19.2.0'}

Body:
Try to add the firebase sdk library in the build.gradle file.

implementation 'com.google.firebase:firebase-core:17.0.0'


问:
Call void method from another method in the same class
At first my main problem was at how to call a method from the same class, even tough I think I found a way to do this, it's not working as I expected, and I would like to know what would be the best approach to my case.

This is the code I'm working on:

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

    private ViewPager mSlideViewPager;
    private LinearLayout mDotLayout;

    String TAG = "TasksSample";

    private TextView[] mDots;

    private SliderAdapter sliderAdapter;
    Dialog myDialog;

    @Override
    public void onCreate (Bundle SavedInstanceState){
        super.onCreate(SavedInstanceState);
        setContentView(R.layout.escolha_atendimento);

        mSlideViewPager = findViewById(R.id.slideViewPager);
        mDotLayout = findViewById(R.id.dotsLayout);

        sliderAdapter = new SliderAdapter(this);
        mSlideViewPager.setAdapter(sliderAdapter);
        addDotsIndicator(0);
        mSlideViewPager.addOnPageChangeListener(viewListener);
        myDialog = new Dialog(this);
    }

    public void addDotsIndicator(int position){

        mDots = new TextView[8];
        mDotLayout.removeAllViews();

        for (int  i= 0; i < mDots.length; i++){
            mDots[i] = new TextView(this);
            mDots[i].setText(Html.fromHtml("•"));
            mDots[i].setTextSize(35);
            mDots[i].setTextColor(getResources().getColor(R.color.colorTransparentWhite));

            mDotLayout.addView(mDots[i]);
        }

        if (mDots.length > 0){
            mDots[position].setTextColor(getResources().getColor(R.color.colorWhite));
        }

    }

    ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener(){

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected (int i) {

            switch (i) {

                case 0: {

                    myDialog.show();

                }

                addDotsIndicator(i);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

   public void ShowPopup(View v) {
            TextView txtclose;
            //Button btnFollow;
            myDialog.setContentView(R.layout.pop_upfinal);
            txtclose = myDialog.findViewById(R.id.txtclose);
            txtclose.setText("X");
            //btnFollow = (Button) myDialog.findViewById(R.id.btnfollow);
            txtclose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    myDialog.dismiss();
                }
            });
            myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            myDialog.show();
    }
}
</code>```

This class is an activity that on user swipe, the text and image from the buttons will change, even though their IDs will stay the same. (That's controlled by another class, it's working well).

Now, I wanted the image button on the activity do something different depending on which page is selected, and that's why there is a initial switch on the onPageSelected method, inside the Page change listener. The image button in the layout has the android:onClick="ShowPopup" tag, and I guess that also complicates things for me, if I wanted it to do something different in that same activity? Also, calling it that way on the switch, every time I change pages, and go back to the first one the popup window will open, since my call is explicit there. (As I said, even tough I found a way to somehow call my method, or at least it's result, it's not working as I expected).

Edit

I tried then changing it like this, so that the button wouldn't rely on the android:onClick="ShowPopup" Tag, and also wouldn't need to call a void method directly on the switch:

Added

```<code>public ImageButton popupchoice;
</code>```

And also this to onCreate method:

```<code>popupchoice = this.findViewById(R.id.imgslide1);
</code>```

Inside the switch I called it like this to get the button ID:

```<code>popupchoice.setOnClickListener(image1);
</code>```

And set the View.OnClickListener like this:

```<code>View.OnClickListener image1 = new View.OnClickListener() {
        public void onClick(View v) {
            TextView txtclose;
            //Button btnFollow;
            myDialog.setContentView(R.layout.pop_upfinal);
            txtclose = myDialog.findViewById(R.id.txtclose);
            txtclose.setText("X");
            //btnFollow = (Button) myDialog.findViewById(R.id.btnfollow);
            txtclose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    myDialog.dismiss();
                }
            });
            myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            myDialog.show();
        }
    };
</code>```

But that returns me:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at .EscolhaAtendimento$1.onPageSelected(EscolhaAtendimento.java:81)

 Line 81 is the one inside the switch with the popupchoice.setOnClickListener(image1).

This error happens on page change, when coming back to the first Page, and also the button click won't work anymore.

答:
I think you can use

EscolhaAtendimento.this.ShowPopup from inside your switch.

Body:
At first my main problem was at how to call a method from the same class, even tough I think I found a way to do this, it's not working as I expected, and I would like to know what would be the best approach to my case.

This is the code I'm working on:

public class EscolhaAtendimento extends AppCompatActivity {

    private ViewPager mSlideViewPager;
    private LinearLayout mDotLayout;

    String TAG = "TasksSample";

    private TextView[] mDots;

    private SliderAdapter sliderAdapter;
    Dialog myDialog;

    @Override
    public void onCreate (Bundle SavedInstanceState){
        super.onCreate(SavedInstanceState);
        setContentView(R.layout.escolha_atendimento);

        mSlideViewPager = findViewById(R.id.slideViewPager);
        mDotLayout = findViewById(R.id.dotsLayout);

        sliderAdapter = new SliderAdapter(this);
        mSlideViewPager.setAdapter(sliderAdapter);
        addDotsIndicator(0);
        mSlideViewPager.addOnPageChangeListener(viewListener);
        myDialog = new Dialog(this);
    }

    public void addDotsIndicator(int position){

        mDots = new TextView[8];
        mDotLayout.removeAllViews();

        for (int  i= 0; i < mDots.length; i++){
            mDots[i] = new TextView(this);
            mDots[i].setText(Html.fromHtml("•"));
            mDots[i].setTextSize(35);
            mDots[i].setTextColor(getResources().getColor(R.color.colorTransparentWhite));

            mDotLayout.addView(mDots[i]);
        }

        if (mDots.length > 0){
            mDots[position].setTextColor(getResources().getColor(R.color.colorWhite));
        }

    }

    ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener(){

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected (int i) {

            switch (i) {

                case 0: {

                    myDialog.show();

                }

                addDotsIndicator(i);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

   public void ShowPopup(View v) {
            TextView txtclose;
            //Button btnFollow;
            myDialog.setContentView(R.layout.pop_upfinal);
            txtclose = myDialog.findViewById(R.id.txtclose);
            txtclose.setText("X");
            //btnFollow = (Button) myDialog.findViewById(R.id.btnfollow);
            txtclose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    myDialog.dismiss();
                }
            });
            myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            myDialog.show();
    }
}

This class is an activity that on user swipe, the text and image from the buttons will change, even though their IDs will stay the same. (That's controlled by another class, it's working well).

Now, I wanted the image button on the activity do something different depending on which page is selected, and that's why there is a initial switch on the onPageSelected method, inside the Page change listener. The image button in the layout has the android:onClick="ShowPopup" tag, and I guess that also complicates things for me, if I wanted it to do something different in that same activity? Also, calling it that way on the switch, every time I change pages, and go back to the first one the popup window will open, since my call is explicit there. (As I said, even tough I found a way to somehow call my method, or at least it's result, it's not working as I expected).

Edit

I tried then changing it like this, so that the button wouldn't rely on the android:onClick="ShowPopup" Tag, and also wouldn't need to call a void method directly on the switch:

Added

public ImageButton popupchoice;

And also this to onCreate method:

popupchoice = this.findViewById(R.id.imgslide1);

Inside the switch I called it like this to get the button ID:

popupchoice.setOnClickListener(image1);

And set the View.OnClickListener like this:

View.OnClickListener image1 = new View.OnClickListener() {
        public void onClick(View v) {
            TextView txtclose;
            //Button btnFollow;
            myDialog.setContentView(R.layout.pop_upfinal);
            txtclose = myDialog.findViewById(R.id.txtclose);
            txtclose.setText("X");
            //btnFollow = (Button) myDialog.findViewById(R.id.btnfollow);
            txtclose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    myDialog.dismiss();
                }
            });
            myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            myDialog.show();
        }
    };

But that returns me:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at .EscolhaAtendimento$1.onPageSelected(EscolhaAtendimento.java:81)

 Line 81 is the one inside the switch with the popupchoice.setOnClickListener(image1).

This error happens on page change, when coming back to the first Page, and also the button click won't work anymore.


问:
Integrate webSDK with jQuery Inside Vue Component?
I am trying to integrate the webSDK from https://www.pollfish.com/docs/webplugin in our Vue app.

Ideally I want to load jquery only in one component.

I wrote the following code but when I click the button it doesnt work.

Here is an example with working code that does NOT use Vue https://github.com/pollfish/webplugin-rewarded-example/blob/master/index.html but does run locally.

I get no errors and I can console.log(Pollfish) inside the the showFullSurvey method.

My code is:

```<code><template>
    <div class="container" v-if="isFreePlan">
        <h2>Remove ads and save unlimited projects for 5 days</h2>
        <button @click="showFullSurvey">Take {{lengthOfInteraction}} Survey Now</button>
    </div>
</template>

<script>
import { mapGetters } from 'vuex';

export default {
    data() {
        return {
            surveyAvailable: false,
            lengthOfInteraction: ''
        }
    },
    methods: {
        showFullSurvey() {
            Pollfish.showFullSurvey();
            console.log('show survey')
        }
    },
    mounted() {
        const pollFishConfig = {
            api_key: "api-key",
            debug: process.env.NODE_ENV === 'production' ? false : true,
            ready: () => {},
            uuid: this.userId,
            surveyAvailable: onSurveyAvailable,
            surveyNotAvailable: onSurveyNotAvailable,
            surveyCompletedCallback: onSurveyCompleted,
            userNotEligibleCallback: onUserDisqualified
        };
        console.log('POllfish config');

        const onSurveyAvailable = (data) => {
            console.log('SUrvey Available');
        };
        const onSurveyNotAvailable = () => {
            console.log('SUrvey Not Available');
        };
        const onSurveyCompleted = () => {
            console.log('SUrvey Completed');
        };
        const onUserDisqualified = () => {
            console.log('USer Disqualified');
        };
        this.addJQuery;
        this.addPollFishSDK;
    },
    computed: {
        ...mapGetters("session", ['userId']),
        ...mapGetters("account", ["isFreePlan"]),
        addJQuery() {
            const url = 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js';
            if(document.querySelector(`script[src='${url}']`)){ return; }
            let jquery = document.createElement('script');
            jquery.setAttribute('src', url);
            document.body.appendChild(jquery);
            console.log('jquery script')
        },
        addPollFishSDK() {
            const url = 'https://storage.googleapis.com/pollfish_production/sdk/webplugin/pollfish.min.js';
            if(document.querySelector(`script[src='${url}']`)){ return; }
            let pollFishSdk = document.createElement('script');
            pollFishSdk.setAttribute('src', url);
            document.body.appendChild(pollFishSdk);
            console.log('pollfish script')
        }
    }
}
</script>
</code>```

答:
In order to integrate our web plugin in your Vue.js app, you need to set the pollfishConfig object in the window. Please be careful with the object's name to be exactly the same as the following example.

window.pollfishConfig = {
  api_key: "api-key",
  debug: process.env.NODE_ENV === 'production' ? false : true,
  ready: () => {},
  uuid: this.userId,
  surveyAvailable: onSurveyAvailable,
  surveyNotAvailable: onSurveyNotAvailable,
  surveyCompletedCallback: onSurveyCompleted,
  userNotEligibleCallback: onUserDisqualified
};
```

<p>Also, based on your example, you need to be sure that the jQuery library is loaded first and be available for our WebPlugin SDK. So you need to handle the <code>onload</code> event. An example solution based on your code is the following:</p>

<pre class="lang-js prettyprint-override"><code>const addScript = (url, onLoad) => {
  const scriptExists = document.querySelector(`script[src='${url}']`);

  if (!scriptExists) {
    let script = document.createElement('script');

    document.body.appendChild(script);

    script.onload = () => {
      onLoad && onLoad();
    }

    script.src = url;
  }
}

addScript('https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', () => {
  addScript('https://storage.googleapis.com/pollfish_production/sdk/webplugin/pollfish.min.js')
});
</code>```

Body:
I am trying to integrate the webSDK from https://www.pollfish.com/docs/webplugin in our Vue app.

Ideally I want to load jquery only in one component.

I wrote the following code but when I click the button it doesnt work.

Here is an example with working code that does NOT use Vue https://github.com/pollfish/webplugin-rewarded-example/blob/master/index.html but does run locally.

I get no errors and I can console.log(Pollfish) inside the the showFullSurvey method.

My code is:

<template>

Remove ads and save unlimited projects for 5 days

        <button @click="showFullSurvey">Take {{lengthOfInteraction}} Survey Now</button>

</template>

Body:
In order to integrate our web plugin in your Vue.js app, you need to set the pollfishConfig object in the window. Please be careful with the object's name to be exactly the same as the following example.

window.pollfishConfig = {
  api_key: "api-key",
  debug: process.env.NODE_ENV === 'production' ? false : true,
  ready: () => {},
  uuid: this.userId,
  surveyAvailable: onSurveyAvailable,
  surveyNotAvailable: onSurveyNotAvailable,
  surveyCompletedCallback: onSurveyCompleted,
  userNotEligibleCallback: onUserDisqualified
};

Also, based on your example, you need to be sure that the jQuery library is loaded first and be available for our WebPlugin SDK. So you need to handle the onload event. An example solution based on your code is the following:

const addScript = (url, onLoad) => {
  const scriptExists = document.querySelector(`script[src='${url}']`);

  if (!scriptExists) {
    let script = document.createElement('script');

    document.body.appendChild(script);

    script.onload = () => {
      onLoad && onLoad();
    }

    script.src = url;
  }
}

addScript('https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', () => {
  addScript('https://storage.googleapis.com/pollfish_production/sdk/webplugin/pollfish.min.js')
});


问:
Invalid Grant error while generation access token Docusign Salesforce API integration
enter image description hereI created Sandbox developer docusign account to integrate Salesforce with Docusign and I am using this documentation link to authenticate Docusign i.e. https://developers.docusign.com/esign-rest-api/guides/authentication/oauth2-code-grant

and I am successfully able to generate authorisation code but getting an INVALID GRANT error while generating access token
CURL used to generate i.e.

curl --data
  grant_type=authorization_code&code=eyJ0eXAiOiJNVCIsImFsZyI6IlJTMjU2Iiwia2lkIjoiNjgxODVmZjEtNGU1MS00Y2U5LWFmMWMtNjg5ODEyMjAzMzE3In0.AQkAAAABAAYABwCAjeI4mg3WSAgAgBlpgJoN1kgCAPoH-9oYVs9NtnQkVw517wIVAAEAAAAYAAEAAAAFAAAADQAkAAAAOGFhZWE4NDktMzQ5Ni00MWQ3LTlkMmYtZmVmZmNmMjA5MTEyMACAjeI4mg3WSBIAAQAAAAsAAABpbnRlcmFjdGl2ZQ.iqqgTue9mRNHQDL9CALsutAMgz6WreewSUqs39K1tSIuYMM8ADK9gp5FzFPb6D_Ozxow_AHDI2BGz0kyvN-0hwQ-H8nWmI4XrLeTFjRoWug2LtcE1wOGljTfOG1gc7eL7Xc6JpF86oXOPz7tkT4UQBDrtJ-uYB4XAum7Fa7zi9GcVQgW9bNe4jHfoLc8F3vKht3ZqjFh6KsWp3npqK62DUbdEX1QOVjUjxPXTsW4XOkhOZMxhm0h3bGPQu94NCGfgZ3EQ3tsISg5fPyu1YiYOmu2olLKb2VOc25l8SjAKXz5KH29iz5N5DpGSKZZQJI3g-QHddj3yUEXc7ndm861mQ

--header Authorization: Basic [[redacted]]

--request POST https://account-d.docusign.com/oauth/token

Please let me know what I am missing while generating access token.

[![enter image description here][2]][2]

enter image description here

答:
DocuSign has recently updated the OAuth workflow so that there will be an error_description in addition to the error_code.

Common issues include:

Expired Code (the code only lasts for a minute or two)

Invalid Client ID or Secret in the Auth header

Incorrect environment (Trying to make a Demo request against account.docusign.com or a Prod request against account-d.docusign.com)


问:
How to configure OpenShift router for KeyCloak?
I have created two projects in OpenShift.

```<code>browser ---> apps/router ---> apps/gw ---> apps
   \                                \
    \                        (/auth) \---> kc/router ---> kc
     \                                     ^
      \-----------------------------------/
           (kc login page)
</code>```

The first project (apps) contains a microservice application and also has a gateway implemented using Netflix Zuul proxy. The second project (kc) has a running KeyCloak instance that can also be reached from outside via a configured route.

Zuul proxy in apps has a route from /auth to kc/auth.

The UI uses the KeyCloak adapter for authentication. When I call apps/ui the SPA is fetched and I'm redirected to apps/auth for authentication. After giving username/password I should be redirected back to the UI but it does not work. I get an error page with an URL pointing to kc. In KeyCloak log I get the following entry:

10:15:24,969 WARN  [org.keycloak.events] (default task-2) type=LOGIN_ERROR, realmId=NUSS, clientId=null, userId=null, ipAddress=10.3.47.12, error=invalid_code

I found out from KeyCloak docu that there has to be something wrong with proxy configuration. When I call apps/auth/realms/master/.well-known/openid-configuration all URLs are pointing to kc. In the docu section about proxy configuration it says that this response should actually contain URLs to apps.

I think that the route to KeyCloak configured in kc replaces the x-forwarded-host header and other proxy headers with kc instead of just leaving the headers set already set in apps. I already validated that the request leaving Zuul proxy contains the correct proxy forwarding headers.

I now have several questions:

What do I have to do to have KeyCloak work in a separate project?

Is my analysis correct anyway?

How can I eventually configure the route in kc to not replace the proxy headers?

Is there eventually a best practice how to do it?

答:
I managed to make it work. But I did have to install a custom router configuration (Deploying a Customized HAProxy Router). I configured that the x-forwarded-host and and x-forwarded-port headers are passing the router untouched if present.

```<code>  # preserve X-Forwarded-Host Header if already set
  acl no_xhost res.hdr(X-Forwarded-Host) -m len 0
  http-request set-header X-Forwarded-Host %[req.hdr(host)] if no_xhost

  # preserve X-Forwarded-Port Header if already set
  acl no_xport res.hdr(X-Forwarded-Port) -m len 0
  http-request set-header X-Forwarded-Port %[dst_port] if no_xport
</code>```

I also had to set the following property in Zuul config.

```<code>zuul.add-proxy-headers=true
</code>```

I wonder why the default router config does overwrite the headers anyway.
Generally I would say that if a request passes various reverse proxies the proxy headers should not be changed while passing them. Otherwise the service at the end of the chain can never know what URL has been used for the original request. Right?

Body:
I have created two projects in OpenShift.

browser ---> apps/router ---> apps/gw ---> apps
   \                                \
    \                        (/auth) \---> kc/router ---> kc
     \                                     ^
      \-----------------------------------/
           (kc login page)

The first project (apps) contains a microservice application and also has a gateway implemented using Netflix Zuul proxy. The second project (kc) has a running KeyCloak instance that can also be reached from outside via a configured route.

Zuul proxy in apps has a route from /auth to kc/auth.

The UI uses the KeyCloak adapter for authentication. When I call apps/ui the SPA is fetched and I'm redirected to apps/auth for authentication. After giving username/password I should be redirected back to the UI but it does not work. I get an error page with an URL pointing to kc. In KeyCloak log I get the following entry:

10:15:24,969 WARN  [org.keycloak.events] (default task-2) type=LOGIN_ERROR, realmId=NUSS, clientId=null, userId=null, ipAddress=10.3.47.12, error=invalid_code

I found out from KeyCloak docu that there has to be something wrong with proxy configuration. When I call apps/auth/realms/master/.well-known/openid-configuration all URLs are pointing to kc. In the docu section about proxy configuration it says that this response should actually contain URLs to apps.

I think that the route to KeyCloak configured in kc replaces the x-forwarded-host header and other proxy headers with kc instead of just leaving the headers set already set in apps. I already validated that the request leaving Zuul proxy contains the correct proxy forwarding headers.

I now have several questions:

What do I have to do to have KeyCloak work in a separate project?

Is my analysis correct anyway?

How can I eventually configure the route in kc to not replace the proxy headers?

Is there eventually a best practice how to do it?

Body:
I managed to make it work. But I did have to install a custom router configuration (Deploying a Customized HAProxy Router). I configured that the x-forwarded-host and and x-forwarded-port headers are passing the router untouched if present.

  # preserve X-Forwarded-Host Header if already set
  acl no_xhost res.hdr(X-Forwarded-Host) -m len 0
  http-request set-header X-Forwarded-Host %[req.hdr(host)] if no_xhost

  # preserve X-Forwarded-Port Header if already set
  acl no_xport res.hdr(X-Forwarded-Port) -m len 0
  http-request set-header X-Forwarded-Port %[dst_port] if no_xport

I also had to set the following property in Zuul config.

zuul.add-proxy-headers=true

I wonder why the default router config does overwrite the headers anyway.
Generally I would say that if a request passes various reverse proxies the proxy headers should not be changed while passing them. Otherwise the service at the end of the chain can never know what URL has been used for the original request. Right?


问:
Passing variable arguments conditionally
In one of my iPhone application, I need to send the variable arguments to the action sheet conditionally. i.e

```<code>if(condition1)
    otherButtonTitles = @"Button1", @"Button2", nil
else
    otherButtonTitles = @"Button3", @"Button4", nil

UIActionSheet *mediaActionsSheet = [[UIActionSheet alloc] initWithTitle: nil
                                                             delegate: self
                                                    cancelButtonTitle: @"Cancel"
                                               destructiveButtonTitle: nil
                                                    otherButtonTitles: otherButtonTitles];
</code>```

What is the syntax to do this? How should the data type for otherButtonTitles be defined?

答:
Well you could simply create the action sheet within your condition.</p>

```<code>UIActionSheet *mediaActionsSheet;
if(condition1)
    {
   mediaActionsSheet  = [[UIActionSheet alloc] initWithTitle: nil
                                                             delegate: self
                                                    cancelButtonTitle: @"Cancel"
                                               destructiveButtonTitle: nil
                               otherButtonTitles:@"Button1", @"Button2", nil];
}

else

{
mediaActionsSheet  = [[UIActionSheet alloc] initWithTitle: nil
                                                         delegate: self
                                                 cancelButtonTitle: @"Cancel"
                                              destructiveButtonTitle: nil
                                 otherButtonTitles:@"Button3", @"Button4", nil];
}
</code>```

Body:
In one of my iPhone application, I need to send the variable arguments to the action sheet conditionally. i.e

if(condition1)
    otherButtonTitles = @"Button1", @"Button2", nil
else
    otherButtonTitles = @"Button3", @"Button4", nil

UIActionSheet *mediaActionsSheet = [[UIActionSheet alloc] initWithTitle: nil
                                                             delegate: self
                                                    cancelButtonTitle: @"Cancel"
                                               destructiveButtonTitle: nil
                                                    otherButtonTitles: otherButtonTitles];

What is the syntax to do this? How should the data type for otherButtonTitles be defined?

Body:
Well you could simply create the action sheet within your condition.

UIActionSheet *mediaActionsSheet;
if(condition1)
    {
   mediaActionsSheet  = [[UIActionSheet alloc] initWithTitle: nil
                                                             delegate: self
                                                    cancelButtonTitle: @"Cancel"
                                               destructiveButtonTitle: nil
                               otherButtonTitles:@"Button1", @"Button2", nil];
}

else

{
mediaActionsSheet  = [[UIActionSheet alloc] initWithTitle: nil
                                                         delegate: self
                                                 cancelButtonTitle: @"Cancel"
                                              destructiveButtonTitle: nil
                                 otherButtonTitles:@"Button3", @"Button4", nil];
}


问:
NGINX Custom error 500 page is not showing
I'm trying to catch the error 500 that NGINX shows when the / location doesn't exist or is empty.

```<code>server {
    listen       80;
    server_name  localhost;
    root   /usr/share/nginx/html/dist/app;
    index  index.html index.htm;

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
      ssi on;
      root /usr/share/nginx/html/;
      internal;
    }

    location / {
      try_files $uri $uri/ /index.html;
    }
}
</code>```

When I save and test this, NGINX tells me the configuration is valid.
But then when I clear my dist folder, I get the default NGINX error 500.

ls -l of /usr/share/nginx/html/

```<code>-rwxrwxrwx   1 root root     43 Feb 17 15:26 50x.html
drwxrwxrwx   2 root root   4096 Feb 17 15:32 dist
</code>```

How is it that I still get the error 500 from NGINX, instead of the 50x.html doc?

答:
Assuming that /index.html is something that runs interpreted (e.g. PHP-FPM), NGINX will default to showing errors from FastCGI server.

To deliver errors by NGINX, you would want to use fastcgi_intercept_errors:

```<code>fastcgi_intercept_errors off;
</code>```

Similiarly, if you're proxying request to /index.html elsewhere (other than a FastCGI server), you would use proxy_intercept_errors:

```<code>proxy_intercept_errors off;
</code>```

Body:
I'm trying to catch the error 500 that NGINX shows when the / location doesn't exist or is empty.

server {
    listen       80;
    server_name  localhost;
    root   /usr/share/nginx/html/dist/app;
    index  index.html index.htm;

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
      ssi on;
      root /usr/share/nginx/html/;
      internal;
    }

    location / {
      try_files $uri $uri/ /index.html;
    }
}

When I save and test this, NGINX tells me the configuration is valid.
But then when I clear my dist folder, I get the default NGINX error 500.

ls -l of /usr/share/nginx/html/

-rwxrwxrwx   1 root root     43 Feb 17 15:26 50x.html
drwxrwxrwx   2 root root   4096 Feb 17 15:32 dist

How is it that I still get the error 500 from NGINX, instead of the 50x.html doc?

Body:
Assuming that /index.html is something that runs interpreted (e.g. PHP-FPM), NGINX will default to showing errors from FastCGI server.

To deliver errors by NGINX, you would want to use fastcgi_intercept_errors:

fastcgi_intercept_errors off;

Similiarly, if you're proxying request to /index.html elsewhere (other than a FastCGI server), you would use proxy_intercept_errors:

proxy_intercept_errors off;


问:
Sql Server string to date conversion
I want to convert a string like this:

```<code>'10/15/2008 10:06:32 PM'
</code>```

into the equivalent DATETIME value in Sql Server.

In Oracle, I would say this:

```<code>TO_DATE('10/15/2008 10:06:32 PM','MM/DD/YYYY HH:MI:SS AM')
</code>```

This question implies that I must parse the string into one of the standard formats, and then convert using one of those codes.  That seems ludicrous for such a mundane operation.  Is there an easier way?

答:
convert string to datetime in MSSQL implicitly</p>

```<code>create table tmp
(
  ENTRYDATETIME datetime
);

insert into tmp (ENTRYDATETIME) values (getdate());
insert into tmp (ENTRYDATETIME) values ('20190101');  --convert string 'yyyymmdd' to datetime

select * from tmp where ENTRYDATETIME > '20190925'  --yyyymmdd
select * from tmp where ENTRYDATETIME > '20190925 12:11:09.555'--yyyymmdd HH:MIN:SS:MS

</code>```

OwnerDisplayName: kogus

Title: Sql Server string to date conversion

Body:
I want to convert a string like this:

'10/15/2008 10:06:32 PM'

into the equivalent DATETIME value in Sql Server.

In Oracle, I would say this:

TO_DATE('10/15/2008 10:06:32 PM','MM/DD/YYYY HH:MI:SS AM')

This question implies that I must parse the string into one of the standard formats, and then convert using one of those codes.  That seems ludicrous for such a mundane operation.  Is there an easier way?

LastEditorDisplayName: Kevin Fairchild

Body:
convert string to datetime in MSSQL implicitly

create table tmp
(
  ENTRYDATETIME datetime
);

insert into tmp (ENTRYDATETIME) values (getdate());
insert into tmp (ENTRYDATETIME) values ('20190101');  --convert string 'yyyymmdd' to datetime

select * from tmp where ENTRYDATETIME > '20190925'  --yyyymmdd
select * from tmp where ENTRYDATETIME > '20190925 12:11:09.555'--yyyymmdd HH:MIN:SS:MS


问:
Arrange boxplots as a grid with seaborn `FacetGrid`
I have a data frame with three columns Features, CV-fold, Accuracy, Network. I want to have a boxplot for each Network, grouped by the Features and the CV-fold for the axis (see example image).

```<code>df = pd.read_csv(path)
df['Features'] = df["Features"].astype('category')
ordered_features = sorted(df.Network.value_counts().index)

df = df.loc[df['Accuracy'] > 0.1]
df.Accuracy = df.Accuracy*100

#sns.color_palette("husl", len(df['CV-fold'].value_counts().index))
#sns.set_palette('husl', len(df['CV-fold'].value_counts().index))

g = sns.FacetGrid(df, row="Network", row_order=ordered_features,
                  height=3, aspect=3, legend_out=True, despine=False)
g.map(sns.boxplot, x="CV-fold", y="Accuracy", hue="Features", data=df, palette='muted').add_legend()

g.set_axis_labels("", "Accuracy (%)")
</code>```

Because I have 8 different networks, I would like to not have them all in a column or a row, but formatted in a grid (e.g. 2x4). Additionally, even though sharex is not enabled, the x-axis is only labeled at the very bottom graph.

How can I do that?

答:
You would use the col_wrap keyword argument to get your plots on multiple rows with multiple columns.

For repeating the x-axis labels use ax.tick_params().

Example:

```<code>import seaborn as sns, matplotlib.pyplot as plt

tips = sns.load_dataset('tips')
ordered_days = sorted(tips['day'].unique())
g = sns.FacetGrid(tips,col='day',col_order=ordered_days,col_wrap=2)
#                                               change this to 4 ^
g.map(sns.boxplot,'sex','total_bill',palette='muted')
for ax in g.axes.flatten():
    ax.tick_params(labelbottom=True)
plt.tight_layout()
plt.show()
</code>```

Result:

Body:
I have a data frame with three columns Features, CV-fold, Accuracy, Network. I want to have a boxplot for each Network, grouped by the Features and the CV-fold for the axis (see example image).

df = pd.read_csv(path)
df['Features'] = df["Features"].astype('category')
ordered_features = sorted(df.Network.value_counts().index)

df = df.loc[df['Accuracy'] > 0.1]
df.Accuracy = df.Accuracy*100

#sns.color_palette("husl", len(df['CV-fold'].value_counts().index))
#sns.set_palette('husl', len(df['CV-fold'].value_counts().index))

g = sns.FacetGrid(df, row="Network", row_order=ordered_features,
                  height=3, aspect=3, legend_out=True, despine=False)
g.map(sns.boxplot, x="CV-fold", y="Accuracy", hue="Features", data=df, palette='muted').add_legend()

g.set_axis_labels("", "Accuracy (%)")

Because I have 8 different networks, I would like to not have them all in a column or a row, but formatted in a grid (e.g. 2x4). Additionally, even though sharex is not enabled, the x-axis is only labeled at the very bottom graph.

How can I do that?

Body:
You would use the col_wrap keyword argument to get your plots on multiple rows with multiple columns.

For repeating the x-axis labels use ax.tick_params().

Example:

import seaborn as sns, matplotlib.pyplot as plt

tips = sns.load_dataset('tips')
ordered_days = sorted(tips['day'].unique())
g = sns.FacetGrid(tips,col='day',col_order=ordered_days,col_wrap=2)
#                                               change this to 4 ^
g.map(sns.boxplot,'sex','total_bill',palette='muted')
for ax in g.axes.flatten():
    ax.tick_params(labelbottom=True)
plt.tight_layout()
plt.show()

Result:


问:
Error when trying to install SSMS 18.4 version

Not sure if anyone has came across this problem but any help is greatly appreciated.

I have SSMS 18.0 Preview 4 installed on my local machine. Whenever I am trying to install any new released version of SSMS I get below error.

Error: The Generally Available (GA) version of SQL Server Management Studio (SSMS) v18.0 cannot be installed because a pre-release version of SSMS is installed on your computer. Uninstall the pre-release version of SSMS from 'Add/Remove Programs' in the Control Panel and run SSMS setup again.

SO i followed the Error and completely removed Preview version. And when i am running new SSMS set up file it still showing same error though i do not have Preview version installed on. I restarted machine after uninstall as well.

Though in error image it says set up is blocked but when i run the SSMS 18 prview 4 it doesn't give me this error and take me to install click.

Any thoughts or solution will highly helpful.

Thank you.

答:
In my case, I was getting the error "SSMSCurrentlyRunning = SSMS is currently running. Please close any open instances of SSMS and run this installer again."

I downloaded the file again and it worked.


问:
How to convert Xamarin.Forms XAML UI page to PDF file?
In Xamarin.Forms, I want to convert my xaml page UI (sometimes my page is scrollable when having more content) into the PDF. I have tried the PDFSharp (https://github.com/akgulebubekir/PDFSharp.Xamarin.Forms) open source. But it works only on UWP and having some issues in iOS and Android.

So is there any free open source plugin available to convert XAML UI into PDF in all three platforms? If open source not available, is there any other way or work around to achieve it in android, ios & UWP?

Thanks in advance.

答:
I had a bit of trouble with this and managed to do it using UIkit and PdfKit tools.

Here is an example:

```<code>using UIKit;
using PdfKit;

//Calculate scroll View height
double xamlHeight = XamlFullPage.Height;
int numberOfPages = (int)Math.Ceiling(xamlHeight / Application.Current.MainPage.Height);

// Create a new PDF document
PdfDocument document = new PdfDocument();

for (int i = 0; i<numberOfPages; i++) //while all the page have not been taken into account
{
        await SummaryScrollView.ScrollToAsync(0, i*Application.Current.MainPage.Height, false).ConfigureAwait(false); //find the beginning of the current page
        //Captures the XAML page as an image and returns the image in memory stream
        var image = UIScreen.MainScreen.Capture();
        // Create a page with the printscreen
        PdfPage page = new PdfPage(image);
        //insert page in the i position
        document.InsertPage(page, i);
        page.Dispose();
}

//Write file in temp folder
          document.Write(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "TuitionFees" + fileName + ".pdf"));`

</code>```

Body:
I had a bit of trouble with this and managed to do it using UIkit and PdfKit tools.

Here is an example:

using UIKit;
using PdfKit;

//Calculate scroll View height
double xamlHeight = XamlFullPage.Height;
int numberOfPages = (int)Math.Ceiling(xamlHeight / Application.Current.MainPage.Height);

// Create a new PDF document
PdfDocument document = new PdfDocument();

for (int i = 0; i<numberOfPages; i++) //while all the page have not been taken into account
{
        await SummaryScrollView.ScrollToAsync(0, i*Application.Current.MainPage.Height, false).ConfigureAwait(false); //find the beginning of the current page
        //Captures the XAML page as an image and returns the image in memory stream
        var image = UIScreen.MainScreen.Capture();
        // Create a page with the printscreen
        PdfPage page = new PdfPage(image);
        //insert page in the i position
        document.InsertPage(page, i);
        page.Dispose();
}

//Write file in temp folder
          document.Write(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "TuitionFees" + fileName + ".pdf"));`


问:
Conflic with shared React custom hook and window.onscroll property
I've a React custom hook that shows/hidden a button according to window.pageYOffset values:

const useHandlerOnScroll = height => {

    const [buttonVisible, showUpButton] = useState(false);
    useEffect ( () => {
        window.onscroll = () => {
            window.pageYOffset >= height ? showUpButton(true) : showUpButton(false)
        }
    })

    return { buttonVisible }
}
```

<p>Whenever I need to use it I just deconstruct my hook in my component and take the buttonVisible value:</p>

<pre class="lang-js prettyprint-override"><code>export default () => {

    const { buttonVisible } = useHandlerOnScroll(450)

    const goTop = () => window.scrollTo({ top: 0, behavior: 'smooth' })

    return buttonVisible
      ? <BottoneTop onClick={() => }> <FaChevronCircleUp /> </BottoneTop>
        : null
}
</code>```

This procedure works as long as I use it only for one component, if I export my useHandlerOnScroll hook and use it on another button then only one button shows up.

I don't understand why, since I thought that every component that imports the hook will create a new instance of that hook.

I also tried useReducer but the result is the same: I canno't use the hook with more than one component.

PS: my guess is that the window.oncroll property is causing some conflict when called like that (I still would prefer not to use addEventListener due to performance reasons).

答:
Just discovered that .onscroll method can only be asigned one object at time, so that's the origin of the conflict:

Only one onscroll handler can be assigned to an object at a time. For greater flexibility, you can pass a scroll event to the EventTarget.addEventListener() method instead.

from: MDN Web docs - GlobalEventHandlers.onscroll

I fixed my problem with window.addEventListener("scroll", callbackFunction ).

Body:
I've a React custom hook that shows/hidden a button according to window.pageYOffset values:

const useHandlerOnScroll = height => {

    const [buttonVisible, showUpButton] = useState(false);
    useEffect ( () => {
        window.onscroll = () => {
            window.pageYOffset >= height ? showUpButton(true) : showUpButton(false)
        }
    })

    return { buttonVisible }
}

Whenever I need to use it I just deconstruct my hook in my component and take the buttonVisible value:

export default () => {

    const { buttonVisible } = useHandlerOnScroll(450)

    const goTop = () => window.scrollTo({ top: 0, behavior: 'smooth' })

    return buttonVisible
      ? <BottoneTop onClick={() => }> <FaChevronCircleUp /> </BottoneTop>
        : null
}

This procedure works as long as I use it only for one component, if I export my useHandlerOnScroll hook and use it on another button then only one button shows up.

I don't understand why, since I thought that every component that imports the hook will create a new instance of that hook.

I also tried useReducer but the result is the same: I canno't use the hook with more than one component.

PS: my guess is that the window.oncroll property is causing some conflict when called like that (I still would prefer not to use addEventListener due to performance reasons).


问:
Javascript: Pass include method to filter array
Filtering arrays in Javascript is possible by passing a custom function to the filter method:

```<code>const bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const filteredArray = bigArray.filter(item => item < 5);
</code>```

It's also possible to pass the function as a "reference":

```<code>function largerThanFive(item) {
  return item => item < 5;
}

const bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const filteredArray = bigArray.filter(largerThanFive);
</code>```

I tried to use this to intersect two arrays via:

```<code>const bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const smallArray = [0, 1, 2];
const filteredArray = bigArray.filter(smallArray.includes);
</code>```

But I get the error:
TypeError: Cannot convert undefined or null to object

I don't understand why. Can someone elaborate on that?

答:
The error TypeError: Cannot convert undefined or null to object is caused when you call a function that expects an Object as its argument, but pass undefined or null instead

You can get each item inside filter, then you can check whether the smallArray has that item like,

```<code>smallArray.includes(item);
</code>```

Snippet as follows:

const bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const smallArray = [0, 1, 2];
const filteredArray = bigArray.filter(item => {
  return smallArray.includes(item);
});

console.log(filteredArray);```

Body:
Filtering arrays in Javascript is possible by passing a custom function to the filter method:

const bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const filteredArray = bigArray.filter(item => item < 5);

It's also possible to pass the function as a "reference":

function largerThanFive(item) {
  return item => item < 5;
}

const bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const filteredArray = bigArray.filter(largerThanFive);

I tried to use this to intersect two arrays via:

const bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const smallArray = [0, 1, 2];
const filteredArray = bigArray.filter(smallArray.includes);

But I get the error:
TypeError: Cannot convert undefined or null to object

I don't understand why. Can someone elaborate on that?

Body:
The error TypeError: Cannot convert undefined or null to object is caused when you call a function that expects an Object as its argument, but pass undefined or null instead

You can get each item inside filter, then you can check whether the smallArray has that item like,

smallArray.includes(item);

Snippet as follows:

const bigArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const smallArray = [0, 1, 2];
const filteredArray = bigArray.filter(item => {
  return smallArray.includes(item);
});

console.log(filteredArray);


问:
jquery hover problem on IE
I have just using the jquery hover :

```<code>$.each(navItems, function(i){
    $(navItems[i]).hover(function(){
        $(this).find('ul:first').css({visibility: "visible",display: "none"}).show();
    },function(){
        $(this).find('ul:first').css({visibility: "hidden"});
    });
});
</code>```

I works fine on all browser except IE. I have looking for the others code that work fine in all major browsers(include IE), normally they also using same the way i did.
Anybody can help me to explain what i wrong?
full code on here : http://jsfiddle.net/XrMNr/

答:
All you need is this:

```<code>$(".NaviItem").hover(function() {
    $(this).find('ul:first').show();
}, function() {
    $(this).find('ul:first').hide();
});
</code>```

Select your target elements simply with .NaviItem. This will return all elements with class NaviItem

You don't need to iterate using each(). In this case the hover handler is applied to all occurrences of .NaviItem

To show/hide you don't need to set the css, just use show() and hide(), or some animation function like fadeOut/fadeIn.

Title: jquery hover problem on IE

Body:
I have just using the jquery hover :

$.each(navItems, function(i){
    $(navItems[i]).hover(function(){
        $(this).find('ul:first').css({visibility: "visible",display: "none"}).show();
    },function(){
        $(this).find('ul:first').css({visibility: "hidden"});
    });
});

I works fine on all browser except IE. I have looking for the others code that work fine in all major browsers(include IE), normally they also using same the way i did.
Anybody can help me to explain what i wrong?
full code on here : http://jsfiddle.net/XrMNr/

Body:
All you need is this:

$(".NaviItem").hover(function() {
    $(this).find('ul:first').show();
}, function() {
    $(this).find('ul:first').hide();
});

Select your target elements simply with .NaviItem. This will return all elements with class NaviItem

You don't need to iterate using each(). In this case the hover handler is applied to all occurrences of .NaviItem

To show/hide you don't need to set the css, just use show() and hide(), or some animation function like fadeOut/fadeIn.


问:
Activiti set tenantId for instance of shared process definition
I am currently considering using Activiti or Camunda in my project. In Camunda I can set a tenantId later on using a so called TenantProvider that is registered upon creating the process engine. I use this to set a tenant to an instance of a shared process definition.

Is this possible in Activiti in one way or another? I found the following call does NOT set the tenant correctly but sets empty string (I believe this is the default tenantId in Activiti since null gives problems with some databases):

```<code>this.runtimeService.createProcessInstanceBuilder()
            .processDefinitionId(processDefinitionId)
            .tenantId(tenantId)
            .start();
</code>```

I use Activiti 6.0.0

PS: I should maybe add for clarification that the deployment and therefore the process definition does NOT have a tenantId because I want it to be used by all tenants.

答:
I asked the same question in the alfresco forum and I was told that this is not possible:

https://hub.alfresco.com/t5/alfresco-process-services/set-tenantid-for-instance-of-shared-process-definition/m-p/294535#M5921

Body:
I am currently considering using Activiti or Camunda in my project. In Camunda I can set a tenantId later on using a so called TenantProvider that is registered upon creating the process engine. I use this to set a tenant to an instance of a shared process definition.

Is this possible in Activiti in one way or another? I found the following call does NOT set the tenant correctly but sets empty string (I believe this is the default tenantId in Activiti since null gives problems with some databases):

this.runtimeService.createProcessInstanceBuilder()
            .processDefinitionId(processDefinitionId)
            .tenantId(tenantId)
            .start();

I use Activiti 6.0.0

PS: I should maybe add for clarification that the deployment and therefore the process definition does NOT have a tenantId because I want it to be used by all tenants.


问:
CSS Alignment Issue on Navigation Bar
I'm currently creating a navigation bar that expands and collapses whether the mouse is over or out of the navbar. My issue is that when the navbar is expanded, my icons are aligned to the center but I wish for them to be positioned exactly where they are before the navbar is expanded. I have them aligned to the center because the icons are not the same size and look 'out of place' without it, when the navbar is collapsed.

let sidenav = document.getElementById("sidenav");
sidenav.onmouseover = function() {
  sidenav.style.width = "280px";
  document.getElementById("expand-icon").classList.add("expand");
  document.getElementById("sidenav-expand").style.textAlign = "right";
  document.getElementById("sidenav-heading").style.display = "inline-block";
  //document.getElementById("links").style.float = "left";
};
sidenav.onmouseout = function() {
  sidenav.style.width = "75px";
  document.getElementById("expand-icon").classList.remove("expand");
  document.getElementById("sidenav-expand").style.textAlign = "center";
  document.getElementById("sidenav-heading").style.display = "none";
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#sidenav {
  height: 100%;
  width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: grey;
  transition: 0.2s;
}

#sidenav-brand {
  padding: 25px 20px;
  background-color: #1a1a27;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

#sidenav-heading h2 {
  margin: 0;
}

#sidenav-expand {
  text-align: center;
  margin-left: 3px;
}

.expand {
  transform: rotate(180deg);
}

#sidenav-links {
  margin: 15px 0;
}

#links {
  list-style-type: none;
  padding: 0;
  text-align: center;
}

#links li {
  padding: 18px;
  display: block;
}

#links li:hover {
  color: white;
  background-color: hotpink;
}</code>```

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>Navigation Bar</title>
  <link href="css/style.css" rel="stylesheet" type="text/css" />

Expanded

```

And JSFiddle link:
https://jsfiddle.net/h86zf4d3/

I tried to float my icons to the left as you can see from the commented out JS code, however, for some reason, this gets rid of the block display for the list items.

答:
Just remove the text-align: center rule on #links element. Also I edited your css to add some :hover rules to avoid using javascript:

#sidenav {
  height: 100%;
  min-width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: grey;
  transition: 0.2s;
}

#sidenav:hover {
  width: 280px;
}

#sidenav:hover #expand-icon {
  transform: rotate(180deg);
}

#sidenav:hover #sidenav-heading {
  display: inline-block;
}

#sidenav #sidenav-heading {
  display: none;
}

#sidenav-brand {
  padding: 25px 20px;
  background-color: #1a1a27;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

#sidenav-heading h2 {
  margin: 0;
}

#sidenav-expand {
  text-align: center;
  margin-left: 3px;
}

#sidenav-links {
  margin: 15px 0;
}

#links {
  list-style-type: none;
  padding: 0;
}

#links li {
  padding: 18px 20px;
  /* <-- Add some padding*/
  display: block;
}

#links li:hover {
  color: white;
  background-color: hotpink;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>Navigation Bar</title>
  <link href="css/style.css" rel="stylesheet" type="text/css" />
  <script src="https://kit.fontawesome.com/6cc49d804e.js" crossorigin="anonymous"></script>
  <script src="js/scripts.js"></script>
</head>

<body>
  <div id="sidenav">
    <div id="sidenav-brand">
      <div id="sidenav-heading">
        <h2>Expanded</h2>
      </div>
      <div id="sidenav-expand">
        <i id="expand-icon" class="fas fa-angle-double-right fa-2x"></i>
      </div>
    </div>

    <div id="sidenav-links">
      <ul id="links">
        <li>
          <i class="fas fa-id-card fa-2x"></i>
        </li>
        <li>
          <i class="fas fa-graduation-cap fa-2x"></i>
        </li>
        <li>
          <i class="fas fa-briefcase fa-2x"></i>
        </li>
        <li>
          <i class="fas fa-smile-beam fa-2x"></i>
        </li>
      </ul>
    </div>
  </div>
</body>

</html></code>```

Title: CSS Alignment Issue on Navigation Bar

Body:
I'm currently creating a navigation bar that expands and collapses whether the mouse is over or out of the navbar. My issue is that when the navbar is expanded, my icons are aligned to the center but I wish for them to be positioned exactly where they are before the navbar is expanded. I have them aligned to the center because the icons are not the same size and look 'out of place' without it, when the navbar is collapsed.

let sidenav = document.getElementById("sidenav");
sidenav.onmouseover = function() {
  sidenav.style.width = "280px";
  document.getElementById("expand-icon").classList.add("expand");
  document.getElementById("sidenav-expand").style.textAlign = "right";
  document.getElementById("sidenav-heading").style.display = "inline-block";
  //document.getElementById("links").style.float = "left";
};
sidenav.onmouseout = function() {
  sidenav.style.width = "75px";
  document.getElementById("expand-icon").classList.remove("expand");
  document.getElementById("sidenav-expand").style.textAlign = "center";
  document.getElementById("sidenav-heading").style.display = "none";
};

#sidenav {
  height: 100%;
  width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: grey;
  transition: 0.2s;
}

#sidenav-brand {
  padding: 25px 20px;
  background-color: #1a1a27;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

#sidenav-heading h2 {
  margin: 0;
}

#sidenav-expand {
  text-align: center;
  margin-left: 3px;
}

.expand {
  transform: rotate(180deg);
}

#sidenav-links {
  margin: 15px 0;
}

#links {
  list-style-type: none;
  padding: 0;
  text-align: center;
}

#links li {
  padding: 18px;
  display: block;
}

#links li:hover {
  color: white;
  background-color: hotpink;
}

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>Navigation Bar</title>
  <link href="css/style.css" rel="stylesheet" type="text/css" />

Expanded

And JSFiddle link:
https://jsfiddle.net/h86zf4d3/

I tried to float my icons to the left as you can see from the commented out JS code, however, for some reason, this gets rid of the block display for the list items.

Body:
Just remove the text-align: center rule on #links element. Also I edited your css to add some :hover rules to avoid using javascript:

#sidenav {
  height: 100%;
  min-width: 75px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1e1e2d;
  overflow-x: hidden;
  color: grey;
  transition: 0.2s;
}

#sidenav:hover {
  width: 280px;
}

#sidenav:hover #expand-icon {
  transform: rotate(180deg);
}

#sidenav:hover #sidenav-heading {
  display: inline-block;
}

#sidenav #sidenav-heading {
  display: none;
}

#sidenav-brand {
  padding: 25px 20px;
  background-color: #1a1a27;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

#sidenav-heading h2 {
  margin: 0;
}

#sidenav-expand {
  text-align: center;
  margin-left: 3px;
}

#sidenav-links {
  margin: 15px 0;
}

#links {
  list-style-type: none;
  padding: 0;
}

#links li {
  padding: 18px 20px;
  /* <-- Add some padding*/
  display: block;
}

#links li:hover {
  color: white;
  background-color: hotpink;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>Navigation Bar</title>
  <link href="css/style.css" rel="stylesheet" type="text/css" />
  <script src="https://kit.fontawesome.com/6cc49d804e.js" crossorigin="anonymous"></script>
  <script src="js/scripts.js"></script>
</head>

<body>
  <div id="sidenav">
    <div id="sidenav-brand">
      <div id="sidenav-heading">
        <h2>Expanded</h2>
      </div>
      <div id="sidenav-expand">
        <i id="expand-icon" class="fas fa-angle-double-right fa-2x"></i>
      </div>
    </div>

    <div id="sidenav-links">
      <ul id="links">
        <li>
          <i class="fas fa-id-card fa-2x"></i>
        </li>
        <li>
          <i class="fas fa-graduation-cap fa-2x"></i>
        </li>
        <li>
          <i class="fas fa-briefcase fa-2x"></i>
        </li>
        <li>
          <i class="fas fa-smile-beam fa-2x"></i>
        </li>
      </ul>
    </div>
  </div>
</body>

</html>