问:
Referencing Enum C++ Unreal
I have created an Enum Class in Unreal C++

```<code>#include "GroundDirection.generated.h"

UENUM(BlueprintType)
enum UGroundDirection
{
     BOTTOM = 0,
     LEFT = 1,
     TOP = 2,
     RIGHT = 3
};
</code>```

In C# or Java I could instantiate a copy of this Enum doing something like this:

```<code>GroundDirection groundDirection = GroundDirection.BOTTOM;
</code>```

I thought I could do something similar with Unreal C++

```<code>UGroundDirection groundDirection = UGroundDirection.BOTTOM;
</code>```

However when I do this I get the following error:

error C2228: left of '.BOTTOM' must have class/struct/union

How to I instantiate Enums in light of this error?

答:
I have created an Enum Class in Unreal C++

No, you didn't. You just created a C-style enum.

Also, the UE++ coding standard states that an enum should have an E as a prefix.

So your declaration should actually look like this:

```<code>#include "GroundDirection.generated.h"

UENUM(BlueprintType)
enum class EGroundDirection
{
     BOTTOM = 0,
     LEFT = 1,
     TOP = 2,
     RIGHT = 3
};
</code>```

To access the members of the enum, you access them like they are static members of a class:

```<code>EGroundDirection direction = EGroundDirection::BOTTOM;
</code>```

This is, because you are not accessing a member of an instance, but a declaration which is always done by using :: in C++.

Title: Referencing Enum C++ Unreal

Body:
I have created an Enum Class in Unreal C++

#include "GroundDirection.generated.h"

UENUM(BlueprintType)
enum UGroundDirection
{
     BOTTOM = 0,
     LEFT = 1,
     TOP = 2,
     RIGHT = 3
};

In C# or Java I could instantiate a copy of this Enum doing something like this:

GroundDirection groundDirection = GroundDirection.BOTTOM;

I thought I could do something similar with Unreal C++

UGroundDirection groundDirection = UGroundDirection.BOTTOM;

However when I do this I get the following error:

error C2228: left of '.BOTTOM' must have class/struct/union

How to I instantiate Enums in light of this error?

Body:
I have created an Enum Class in Unreal C++

No, you didn't. You just created a C-style enum.

Also, the UE++ coding standard states that an enum should have an E as a prefix.

So your declaration should actually look like this:

#include "GroundDirection.generated.h"

UENUM(BlueprintType)
enum class EGroundDirection
{
     BOTTOM = 0,
     LEFT = 1,
     TOP = 2,
     RIGHT = 3
};

To access the members of the enum, you access them like they are static members of a class:

EGroundDirection direction = EGroundDirection::BOTTOM;

This is, because you are not accessing a member of an instance, but a declaration which is always done by using :: in C++.


来源: stackexchange

问:
Is there a way to make an element spin around without a variable telling how far it has already turned?
I have an experimental website that plays music, and I want the forward and backward buttons to spin when you click them. But, I also don't want to have 2 variables to be how far they have turned, or a function to get how far they have turned from the CSS transform property. They have a transition, for hover effects. I have tried </p>

```<code>    backward.classList.add("notrans");
    backward.style.transform = "rotateZ(0deg)";
    backward.classList.remove("notrans");
    backward.style.transform = "rotateZ(-360deg)";
</code>```

<p>and some closely related things, and also have a setTimeout to reset it afterwards, which it too long for a post. </p>

答:
Animate is what you are searching for.
This should be a working example: (Tested in FF and Chrome)

/* THIS IS A JAVASCRIPT CLASS THAT ADDS AND
REMOVES THE CSS CLASS FROM YOUR ELEMENT
USING THE ELEMENT'S ID VALUE TO REFERENCE. */

function startStop(strstp) {
  var infinite = document.getElementById("imSpinning");
  var once = document.getElementById("imSpinningOnce");

  if(strstp == 1)
  {
    infinite.classList.add("spin");
    once.classList.add("spinOnce");
    timer = setTimeout(function() {
      once.classList.remove("spinOnce");
    },1000);
  }
  else
  {
    infinite.classList.remove("spin");
    once.classList.remove("spinOnce");
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* THIS IS THE CSS CLASS THAT CREATES INFINITE ROTATION */

.spin {
    -webkit-animation:spin 1s linear infinite;
    -moz-animation:spin 1s linear infinite;
    animation:spin 1s linear infinite;
}
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }

/* THIS IS THE CSS CLASS THAT ROTATES ONCE */

.spinOnce {
    -webkit-animation:spin 1s linear;
    -moz-animation:spin 1s linear;
    animation:spin 1s linear;
}
@-moz-keyframes spinOnce { 100% { -moz-transform: rotate(360deg); } }
@-webkit-keyframes spinOnce { 100% { -webkit-transform: rotate(360deg); } }
@keyframes spinOnce { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }</code>```

GO

STOP

```

Simply copy the CSS class above to the style section/sheet of your page and modify it as needed. Ensure you reference the class in your html element.

Also I edited in a small JavaScript class that add/removes the spin class from the DIV element if it helps you in starting and stopping the animation.

Hope this helps, and best of luck!

ContentLicense: CC BY-SA 4.0

Body:
I have an experimental website that plays music, and I want the forward and backward buttons to spin when you click them. But, I also don't want to have 2 variables to be how far they have turned, or a function to get how far they have turned from the CSS transform property. They have a transition, for hover effects. I have tried

    backward.classList.add("notrans");
    backward.style.transform = "rotateZ(0deg)";
    backward.classList.remove("notrans");
    backward.style.transform = "rotateZ(-360deg)";

and some closely related things, and also have a setTimeout to reset it afterwards, which it too long for a post.

Body:
Animate is what you are searching for.
This should be a working example: (Tested in FF and Chrome)

/* THIS IS A JAVASCRIPT CLASS THAT ADDS AND
REMOVES THE CSS CLASS FROM YOUR ELEMENT
USING THE ELEMENT'S ID VALUE TO REFERENCE. */

function startStop(strstp) {
  var infinite = document.getElementById("imSpinning");
  var once = document.getElementById("imSpinningOnce");

  if(strstp == 1)
  {
    infinite.classList.add("spin");
    once.classList.add("spinOnce");
    timer = setTimeout(function() {
      once.classList.remove("spinOnce");
    },1000);
  }
  else
  {
    infinite.classList.remove("spin");
    once.classList.remove("spinOnce");
  }
}

/* THIS IS THE CSS CLASS THAT CREATES INFINITE ROTATION */

.spin {
    -webkit-animation:spin 1s linear infinite;
    -moz-animation:spin 1s linear infinite;
    animation:spin 1s linear infinite;
}
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }

/* THIS IS THE CSS CLASS THAT ROTATES ONCE */

.spinOnce {
    -webkit-animation:spin 1s linear;
    -moz-animation:spin 1s linear;
    animation:spin 1s linear;
}
@-moz-keyframes spinOnce { 100% { -moz-transform: rotate(360deg); } }
@-webkit-keyframes spinOnce { 100% { -webkit-transform: rotate(360deg); } }
@keyframes spinOnce { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }

<div style="width: 100px; height: 30px; background-color: green; color: white; margin: 20px; text-align: center; cursor: pointer;" onclick="startStop(1)">
GO
</div>

<div style="width: 100px; height: 30px; background-color: red; color: white; margin: 20px; text-align: center; cursor: pointer;" onclick="startStop(0)">
STOP
</div>

<!-- ELEMENT TO ROTATE INFINITLY WITH "spin" CLASS -->
<div id="imSpinning" class="spin" style="position: absolute; top: 10px; right: 30px; height: 140px; width: 140px; background-image: url(https://icons.iconarchive.com/icons/thehoth/seo/256/seo-web-code-icon.png); background-size: 100% 100%; background-position: center center; border-radius: 50%; overflow: hidden;"></div>

<!-- ELEMENT TO ROTATE ONCE WITH "spin" CLASS -->
<div id="imSpinningOnce" class="spinOnce" style="position: absolute; top: 10px; right: 200px; height: 140px; width: 140px; background-image: url(https://icons.iconarchive.com/icons/thehoth/seo/256/seo-web-code-icon.png); background-size: 100% 100%; background-position: center center; border-radius: 50%; overflow: hidden;"></div>

Simply copy the CSS class above to the style section/sheet of your page and modify it as needed. Ensure you reference the class in your html element.

Also I edited in a small JavaScript class that add/removes the spin class from the DIV element if it helps you in starting and stopping the animation.

Hope this helps, and best of luck!


问:
Angular login page
I’m new to Angular. I’ve been watching tutorials on YouTube and all of them teach routing with a sticky navigation bar. Is it possible to click on a link and navigate into a completely new page without the navigation bar?

This is the index.html displaying. The blue words are navigation and are routed.

I’m trying to route into the Login Page without the navigation bar showing. Is it possible to do that?

Here is the code for the index.html and the app.component.html just in case its necessary

答:
Yes it is possible to navigate to the login page and have the navigation bar not showing in that login page.

One way to achieve this, is by removing the navigation bar from view when the current route is /login. Create a boolean property in app.component.ts that will represent if the route's current state is /login.

app.component.ts could look like this:

```<code>    import { Component } from '@angular/core';
    import { Router, NavigationEnd } from '@angular/router';
    import { filter } from 'rxjs/operators';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent {

      isLoginPage: boolean;

      constructor(private router: Router) {
        this.router.events.pipe(
          filter(event => event instanceof NavigationEnd)
        ).subscribe((event: NavigationEnd) => {
          this.isLoginPage = this.router.url === '/login';
        });
      }
    }
</code>```

Then bind this boolean property to the navigation bar with *ngIf directive.

In app.component.html:

```<code>    <div *ngIf="!isLoginPage" id="temporary-navigator style="text-align: center;">
      ...
    </div>
</code>```

Title: Angular login page

Body:
Yes it is possible to navigate to the login page and have the navigation bar not showing in that login page.

One way to achieve this, is by removing the navigation bar from view when the current route is /login. Create a boolean property in app.component.ts that will represent if the route's current state is /login.

app.component.ts could look like this:

    import { Component } from '@angular/core';
    import { Router, NavigationEnd } from '@angular/router';
    import { filter } from 'rxjs/operators';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent {

      isLoginPage: boolean;

      constructor(private router: Router) {
        this.router.events.pipe(
          filter(event => event instanceof NavigationEnd)
        ).subscribe((event: NavigationEnd) => {
          this.isLoginPage = this.router.url === '/login';
        });
      }
    }

Then bind this boolean property to the navigation bar with *ngIf directive.

In app.component.html:

    <div *ngIf="!isLoginPage" id="temporary-navigator style="text-align: center;">
      ...
    </div>


问:
Devextreme dxDataGrid inside dxDataGrid editing
I have a problem about Devextreme..

I want to show dxDatagrid on dxDatagrid - editing popup.

I just want when I clicked 'Edit' show popup and dataGrid inside popup

In react, I Although success like this

```<code>          <Item>
            <DataGrid
              dataSource={employees}></DataGrid>
          </Item>
</code>```

This code here

https://codesandbox.io/s/4z1m9

But in javascript, I don't know how I show that grid..

https://codepen.io/cms010621/pen/vYNqapG

This is the best idea in my head, but not working,, I don't know.. help me..

答:
if you want to complete in this path you have to customize grid popup itself it's a long-hard way.

you can hack and use new dxPopup with your custom content which is grid maybe or forms or whatever components, and config this popup component to accept the data as a props. then at grid you can go with this steeps minimized the popup and passing the data devextreme datagrid command button.

Body:
I have a problem about Devextreme..

I want to show dxDatagrid on dxDatagrid - editing popup.

I just want when I clicked 'Edit' show popup and dataGrid inside popup

In react, I Although success like this

          <Item>
            <DataGrid
              dataSource={employees}></DataGrid>
          </Item>

This code here

https://codesandbox.io/s/4z1m9

But in javascript, I don't know how I show that grid..

https://codepen.io/cms010621/pen/vYNqapG

This is the best idea in my head, but not working,, I don't know.. help me..


问:
html tag attribute "data-setbg" is not working in React project
I'm converting a HTML website template into a React project, in that template there is an attribute called data-setbg, but there is no standard html attribute provided, I wonder what kind of library or framework provide this ability to set HTML's element background image like that? </p>

答:
This one works
Move all code into the $(window).on('load',function(){...})

CSS background-image renders as url('undefined'); even though I defined it. (JSX)


问:
How do I change the body background with CSS depending on the screen size, and if a file exists with PHP?
I hope I can explain what I want to do OK.
My site is built in PHP with pages created from a mySQL database. In this case, I want to change the body background of the project page depending on whether there is an image in the folder that matches the ID of the page (project_id). The following code works fine in accomplishing this:

```<code> <body style="background: url(<?php

 $background = dirname(__FILE__) . "/ $myMedia images/bg/ $row[project_id].jpg";
 $background = str_replace(" ", "", $background);

 if (file_exists($background)) {
     echo "images/bg/$row[project_id].jpg";
 } else {
     echo "images/bg.jpg";
 }

?>) repeat-x;" />
</code>```

However, what I want to do is ONLY change the background of the page if the screen size is larger than 767px, otherwise I want to display a different background for the mobile phone view (bg-mob-380.jpg). I've tried the following code but it doesn't work, and I'm not sure what I'm doing wrong.

```<code> <body style="
@media only screen and (max-width: 767px) {
    background: #FFFFFF url(images/bg-mob-380.jpg) repeat-x;
}
@media only screen and (min-width: 768px) {
 background: url(<?php

 $background = dirname(__FILE__) . "/ $myMedia images/bg/ $row[project_id].jpg";
 $background = str_replace(" ", "", $background);

 if (file_exists($background)) {
     echo "images/bg/$row[project_id].jpg";
 } else {
     echo "images/bg.jpg";
 }

?>) repeat-x;
}
" />
</code>```

Any help would be appreciated. Thanks in advance :)

答:
The url for image should be in single/double quotes:

```<code>@media only screen and (max-width: 767px) {
background: #FFFFFF url('images/bg-mob-380.jpg') repeat-x;
}
@media only screen and (min-width: 768px) {
background: url('<?php

$background = dirname(__FILE__) . "/ $myMedia images/bg/ $row[project_id].jpg";
$background = str_replace(" ", "", $background);

if (file_exists($background)) {
    echo "images/bg/$row[project_id].jpg";
} else {
   echo "images/bg.jpg";
}

?>') repeat-x;
}
" />
</code>```

Edit :- It can be caused because of this variable $row[project_id]  which should be like $row['project_id'] , so try concatenation to work through this.

It should be like this

```<code>$background = dirname(__FILE__) . "/ $myMedia images/bg/". $row['project_id'].".jpg";
</code>```

and

```<code>echo "images/bg/".$row['project_id'].".jpg";
</code>```

Body:
I hope I can explain what I want to do OK.
My site is built in PHP with pages created from a mySQL database. In this case, I want to change the body background of the project page depending on whether there is an image in the folder that matches the ID of the page (project_id). The following code works fine in accomplishing this:

 <body style="background: url(<?php

 $background = dirname(__FILE__) . "/ $myMedia images/bg/ $row[project_id].jpg";
 $background = str_replace(" ", "", $background);

 if (file_exists($background)) {
     echo "images/bg/$row[project_id].jpg";
 } else {
     echo "images/bg.jpg";
 }

?>) repeat-x;" />

However, what I want to do is ONLY change the background of the page if the screen size is larger than 767px, otherwise I want to display a different background for the mobile phone view (bg-mob-380.jpg). I've tried the following code but it doesn't work, and I'm not sure what I'm doing wrong.

 <body style="
@media only screen and (max-width: 767px) {
    background: #FFFFFF url(images/bg-mob-380.jpg) repeat-x;
}
@media only screen and (min-width: 768px) {
 background: url(<?php

 $background = dirname(__FILE__) . "/ $myMedia images/bg/ $row[project_id].jpg";
 $background = str_replace(" ", "", $background);

 if (file_exists($background)) {
     echo "images/bg/$row[project_id].jpg";
 } else {
     echo "images/bg.jpg";
 }

?>) repeat-x;
}
" />

Any help would be appreciated. Thanks in advance :)

Body:
The url for image should be in single/double quotes:

@media only screen and (max-width: 767px) {
background: #FFFFFF url('images/bg-mob-380.jpg') repeat-x;
}
@media only screen and (min-width: 768px) {
background: url('<?php

$background = dirname(__FILE__) . "/ $myMedia images/bg/ $row[project_id].jpg";
$background = str_replace(" ", "", $background);

if (file_exists($background)) {
    echo "images/bg/$row[project_id].jpg";
} else {
   echo "images/bg.jpg";
}

?>') repeat-x;
}
" />

Edit :- It can be caused because of this variable $row[project_id]  which should be like $row['project_id'] , so try concatenation to work through this.

It should be like this

$background = dirname(__FILE__) . "/ $myMedia images/bg/". $row['project_id'].".jpg";

and

echo "images/bg/".$row['project_id'].".jpg";


问:
ReactJS - replacing an object in an array with another
I am working on a project where I have 4 options, but I should only be able to select one option per screen. The option pushes an object with an id and a score (based on the screen) to an array in the state. So if I make one selection and change to another, I'd like to able to remove the previous object and append the new one in an array in the state (for each screen). I have script to append and remove the object if I'm clicking on the same option, but I'm not sure what I would do to replace the object with a new one if I make a selection then immediately go to another.

The array looks as follows:

```<code>scores: [
  [{id: "G1", score: "4"}, {id: "B1", score: "3"}, {id: "O1", score: "2"}, {id: "R1", score: "1"}],
  [{id: "B2", score: "4"}, {id: "G2", score: "3"}, {id: "R2", score: "1"}, {id: "O2", score: "4"}]
]
</code>```

Here is the code I have now:

handleScore = (id, score, idx) => {
  const {
    statements,
    scores
  } = this.state;
  if (statements[0][idx].isSelected) {
    this.setState({
      scores: scores.map((item, index) => index === 0 ? [...item, {
        'id': id,
        'score': score
      }] : item)
    });
  } else {
    this.setState({
      scores: scores.map((item, index) => index === 0 ? item.filter(i => i.id !== item[0].id) : item)
    });
  }
}
```

<p>and in the render method I have:</p>

```<div
  className={`statement ${(this.state.statements[0][index].isSelected) ? 'selected' : ''}`} key={item.id} onClick={e => {
      e.preventDefault();
      this.handleScore(item.id, match.params.score, index)
    }}>
  {item.statement}

```

Thank you in advance!

答:
I don't know what you are trying to do, but you can use the splice() method to remove an item from an array. Check this repro on Stackblitz to see the result, and here is the code in case it does not works:

```<code>import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import "./style.css";

const App = () => {
  const [data, setData] = React.useState([
    {id: 0, score:10},
    {id: 1, score:20},
    {id: 2, score:30},
    {id: 3, score:40},
  ]);

const displayItems = () => {
  return data.map((item, index) => {
    return (
    <div>
      <span>id: {item.id}, score: {item.score}</span>{' '}
      <button onClick={() => replaceItem(item, index)}>Replace item</button>
    </div>
  )});
}

const replaceItem = (item, index) => {
  const newItem = {id:4, score: 50};

  let newData = [...data];

  // -----Replace ONE ('1') item at specific index by the newItem
  // newData.splice(index, 1, newItem);
  // -----OR remove an item and place another at the first index
  newData.splice(index, 1); // remove item from array
  newData.unshift(item); // Put the item at the first index of the array
  //------
  setData(newData); // set your newData array as the new state
}
  return (
    <div>
      {displayItems()}
    </div>
  );
};

render(<App />, document.getElementById("root"));

</code>```

I placed two use case of splice so you can coment/uncomment to see the result.

Body:
I am working on a project where I have 4 options, but I should only be able to select one option per screen. The option pushes an object with an id and a score (based on the screen) to an array in the state. So if I make one selection and change to another, I'd like to able to remove the previous object and append the new one in an array in the state (for each screen). I have script to append and remove the object if I'm clicking on the same option, but I'm not sure what I would do to replace the object with a new one if I make a selection then immediately go to another.

The array looks as follows:

scores: [
  [{id: "G1", score: "4"}, {id: "B1", score: "3"}, {id: "O1", score: "2"}, {id: "R1", score: "1"}],
  [{id: "B2", score: "4"}, {id: "G2", score: "3"}, {id: "R2", score: "1"}, {id: "O2", score: "4"}]
]

Here is the code I have now:

handleScore = (id, score, idx) => {
  const {
    statements,
    scores
  } = this.state;
  if (statements[0][idx].isSelected) {
    this.setState({
      scores: scores.map((item, index) => index === 0 ? [...item, {
        'id': id,
        'score': score
      }] : item)
    });
  } else {
    this.setState({
      scores: scores.map((item, index) => index === 0 ? item.filter(i => i.id !== item[0].id) : item)
    });
  }
}

and in the render method I have:

<div
  className={`statement ${(this.state.statements[0][index].isSelected) ? 'selected' : ''}`} key={item.id} onClick={e => {
      e.preventDefault();
      this.handleScore(item.id, match.params.score, index)
    }}>
  {item.statement}

Thank you in advance!

Body:
I don't know what you are trying to do, but you can use the splice() method to remove an item from an array. Check this repro on Stackblitz to see the result, and here is the code in case it does not works:

import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import "./style.css";

const App = () => {
  const [data, setData] = React.useState([
    {id: 0, score:10},
    {id: 1, score:20},
    {id: 2, score:30},
    {id: 3, score:40},
  ]);

const displayItems = () => {
  return data.map((item, index) => {
    return (
    <div>
      <span>id: {item.id}, score: {item.score}</span>{' '}
      <button onClick={() => replaceItem(item, index)}>Replace item</button>
    </div>
  )});
}

const replaceItem = (item, index) => {
  const newItem = {id:4, score: 50};

  let newData = [...data];

  // -----Replace ONE ('1') item at specific index by the newItem
  // newData.splice(index, 1, newItem);
  // -----OR remove an item and place another at the first index
  newData.splice(index, 1); // remove item from array
  newData.unshift(item); // Put the item at the first index of the array
  //------
  setData(newData); // set your newData array as the new state
}
  return (
    <div>
      {displayItems()}
    </div>
  );
};

render(<App />, document.getElementById("root"));

I placed two use case of splice so you can coment/uncomment to see the result.


问:
Disable plugin contributions in Eclipse RCP Application
I frequently had this problem and didn't find a solution yet: Whenever I write a new Eclipse RCP based application and include plugins from the Eclipse platform, I 'inherit' UI contributions from some of those plugins.

Most of this contributions (menu entries, keyboard shortcuts, property pages) are useful but sometimes I'd rather disabled some of these contributions, just because I really do not need them and they might confuse the users.

Does anyone know of the official or a practical way to disable/prohibit selected contributions in Eclipse RCP applications?

答: Equinox transformations can also be used to supply XLST transformations that remove unwanted UI contributions.</p>

ContentLicense: CC BY-SA 3.0


问:
How to merge two CSV files with Linux column wise?
I am looking for a simple line of code (if possible) to simply merge two files column wise and save the final result into a new file.

Edited to response to the first answer @heitor:

By using paste file1.csv file2.csv, What happened is:

For instance file 1:

```<code>A B
1 2
</code>```

file2:

```<code>C D
3 4
</code>```

By doing paste -d , file1.csv file2.csv >output.csv I got

```<code> A B
 C D
 1 2
 3 4
</code>```

not

```<code>A B C D
1 2 3 4
</code>```

By doing cat file1.csv file2.csv I got

```<code>A B
1 2
C D
3 4
</code>```

Neither of them is what I want. Any idea?

Any idea?

答:
Indeed using paste is pretty simple,

```<code>$ cat file1.csv
A B
1 2

$ cat file2.csv
C D
3 4

$ paste -d " " file1.csv file2.csv
A B C D
1 2 3 4
</code>```

With the -d option I replaced the default tab character with a space.

Edit:

In case you want to redirect that to another file then,

```<code>paste -d " " file1.csv file2.csv > file3.csv
$ cat file3.csv
A B C D
1 2 3 4
</code>```

Body:
I am looking for a simple line of code (if possible) to simply merge two files column wise and save the final result into a new file.

Edited to response to the first answer @heitor:

By using paste file1.csv file2.csv, What happened is:

For instance file 1:

A B
1 2

file2:

C D
3 4

By doing paste -d , file1.csv file2.csv >output.csv I got

 A B
 C D
 1 2
 3 4

not

A B C D
1 2 3 4

By doing cat file1.csv file2.csv I got

A B
1 2
C D
3 4

Neither of them is what I want. Any idea?

Any idea?

Body:
Indeed using paste is pretty simple,

$ cat file1.csv
A B
1 2

$ cat file2.csv
C D
3 4

$ paste -d " " file1.csv file2.csv
A B C D
1 2 3 4

With the -d option I replaced the default tab character with a space.

Edit:

In case you want to redirect that to another file then,

paste -d " " file1.csv file2.csv > file3.csv
$ cat file3.csv
A B C D
1 2 3 4


问:
Pandas groupby concat ungrouped column into comma separated string
I have the following example df:

```<code>        col1     col2    col3   doc_no
     0     a        x       f        0
     1     a        x       f        1
     2     b        x       g        2
     3     b        y       g        3
     4     c        x       t        3
     5     c        y       t        4
     6     a        x       f        5
     7     d        x       t        5
     8     d        x       t        6
</code>```

I want to group by the first 3 columns (col1, col2, col3), concatenate the fourth column (doc_no) into a line of strings based on the groupings of the first 3 columns, as well as also generate a sorted count column of the 3 column grouping (count). Example desired output below (column order doesn't matter):

```<code>        col1     col2    col3   count      doc_no
     0     a        x       f       3     0, 1, 5
     1     d        x       t       2        5, 6
     2     b        x       g       1           2
     3     b        y       g       1           3
     4     c        x       t       1           3
     5     c        y       t       1           4
</code>```

How would I go about doing this? I used the below line to get just the grouping and the count:

```<code>grouped_df = df.groupby(['col1','col2','col3']).size().reset_index(name='count')\
    .sort_values(['count'], ascending=False).reset_index()
</code>```

But I'm not sure how to also get the concatenated doc_no column in the same code line.

答:
Try groupby and agg like so:

```<code>(df.groupby(['col1', 'col2', 'col3'])['doc_no']
   .agg(['count', ('doc_no',  lambda x: ','.join(map(str, x)))])
   .sort_values('count', ascending=False)
   .reset_index())

  col1 col2 col3  count doc_no
0    a    x    f      3  0,1,5
1    d    x    t      2    5,6
2    b    x    g      1      2
3    b    y    g      1      3
4    c    x    t      1      3
5    c    y    t      1      4
</code>```

agg is simple to use because you can specify a list of reducers to run on a single column.

Body:
I have the following example df:

        col1     col2    col3   doc_no
     0     a        x       f        0
     1     a        x       f        1
     2     b        x       g        2
     3     b        y       g        3
     4     c        x       t        3
     5     c        y       t        4
     6     a        x       f        5
     7     d        x       t        5
     8     d        x       t        6

I want to group by the first 3 columns (col1, col2, col3), concatenate the fourth column (doc_no) into a line of strings based on the groupings of the first 3 columns, as well as also generate a sorted count column of the 3 column grouping (count). Example desired output below (column order doesn't matter):

        col1     col2    col3   count      doc_no
     0     a        x       f       3     0, 1, 5
     1     d        x       t       2        5, 6
     2     b        x       g       1           2
     3     b        y       g       1           3
     4     c        x       t       1           3
     5     c        y       t       1           4

How would I go about doing this? I used the below line to get just the grouping and the count:

grouped_df = df.groupby(['col1','col2','col3']).size().reset_index(name='count')\
    .sort_values(['count'], ascending=False).reset_index()

But I'm not sure how to also get the concatenated doc_no column in the same code line.

Body:
Try groupby and agg like so:

(df.groupby(['col1', 'col2', 'col3'])['doc_no']
   .agg(['count', ('doc_no',  lambda x: ','.join(map(str, x)))])
   .sort_values('count', ascending=False)
   .reset_index())

  col1 col2 col3  count doc_no
0    a    x    f      3  0,1,5
1    d    x    t      2    5,6
2    b    x    g      1      2
3    b    y    g      1      3
4    c    x    t      1      3
5    c    y    t      1      4

agg is simple to use because you can specify a list of reducers to run on a single column.


问:
Iterate through firebase values
I would like to access the comments array and do some calculations to render the average of ratings (avgstars) and show the numbers of comments on a particular item in my firebase array.

Any idea?

ngOnInit() {
  this.route.params
    .pipe(switchMap((params: Params) => this.dishservice.getDish(params['id'])))
    .subscribe(dish => {
      this.dish = dish
      this.favorite = this.favoriteService.isFavorite(this.dish.id);

      //compute the average of the comments and the render the length of the array
      this.numcomments = /* This is the locus --->*/ this.dish.comments.length;
      let total =0;
      this.dish.comments.forEach(comment =>total += comment.rating);
      this.avgstars = (total/this.numcomments).toFixed(2);
         },
        errmess => this.errMess = <any>errmess);
      }
```

Here is the data sample

答:
It looks like "comments" is an object and not an array. therefore you will fail getting a number via "length".

you may try it iterate thru the object keys.

see here: How do I loop through or enumerate a JavaScript object?

Title: Iterate through firebase values

Body:
I would like to access the comments array and do some calculations to render the average of ratings (avgstars) and show the numbers of comments on a particular item in my firebase array.

Any idea?

ngOnInit() {
  this.route.params
    .pipe(switchMap((params: Params) => this.dishservice.getDish(params['id'])))
    .subscribe(dish => {
      this.dish = dish
      this.favorite = this.favoriteService.isFavorite(this.dish.id);

      //compute the average of the comments and the render the length of the array
      this.numcomments = /* This is the locus --->*/ this.dish.comments.length;
      let total =0;
      this.dish.comments.forEach(comment =>total += comment.rating);
      this.avgstars = (total/this.numcomments).toFixed(2);
         },
        errmess => this.errMess = <any>errmess);
      }

Here is the data sample


问:
julia struct inner constructor optional type specification
Consider the following struct:

```<code>struct MyType1{T}
    data::T
end
</code>```

It can be instantiated in two ways:

```<code>println(MyType1(5))                 # MyType1{Int64}(5)
println(MyType1{Int}(5))            # MyType1{Int64}(5)
</code>```

When I define something similar with inner constructor:

```<code>struct MyType2{T}
    data::T
    MyType2(x::T) where T = new{T}(x)
end

struct MyType3{T}
    data::T
    MyType3{T}(x::T) where T = new{T}(x)
end
</code>```

I can instantiate them only in one way:

```<code>println(MyType2(5))                 # MyType2{Int64}(5)
println(MyType2{Int}(5))            # MethodError

println(MyType3(5))                 # MethodError
println(MyType3{Int}(5))            # MyType3{Int64}(5)
</code>```

How can I make type specification in inner constructor optional (make MyType2 and MyType3 not to throw MethodError in the example above)?

julia version 1.4.1

答:
Just provide an additional constructor:

```<code>struct MyType4{T}
   data::T
   MyType4{T}(x::T) where T = new{T}(x)
end

MyType4(x::T) where T = MyType4{T}(x)
</code>```

Test

```<code>julia> MyType4{Int}(5)
MyType4{Int64}(5)

julia> MyType4(5)
MyType4{Int64}(5)
</code>```

Body:
Consider the following struct:

struct MyType1{T}
    data::T
end

It can be instantiated in two ways:

println(MyType1(5))                 # MyType1{Int64}(5)
println(MyType1{Int}(5))            # MyType1{Int64}(5)

When I define something similar with inner constructor:

struct MyType2{T}
    data::T
    MyType2(x::T) where T = new{T}(x)
end

struct MyType3{T}
    data::T
    MyType3{T}(x::T) where T = new{T}(x)
end

I can instantiate them only in one way:

println(MyType2(5))                 # MyType2{Int64}(5)
println(MyType2{Int}(5))            # MethodError

println(MyType3(5))                 # MethodError
println(MyType3{Int}(5))            # MyType3{Int64}(5)

How can I make type specification in inner constructor optional (make MyType2 and MyType3 not to throw MethodError in the example above)?

julia version 1.4.1

Body:
Just provide an additional constructor:

struct MyType4{T}
   data::T
   MyType4{T}(x::T) where T = new{T}(x)
end

MyType4(x::T) where T = MyType4{T}(x)

Test

julia> MyType4{Int}(5)
MyType4{Int64}(5)

julia> MyType4(5)
MyType4{Int64}(5)


问:
JEditable using Select on MVC 3
I'm currently want to display a list of data using DataTables. And I want to be able to edit the record inline.  I could execute those with no problem.  The problem is, when I try to use drop down list(select) on one of the field for JEditable, that's when everything stuck to no where.

I would like to fetch the data from one of my table in MSSQL and dump it on data : "{ 'test' : 'test' }" for example.  but I cant find a way to do that. My JS knowledge is not that good.

Is there any way I could execute this? With this question, I include my current codes:
this is my initialization for Datatables and JEditable

```<code>$(document).ready(function () {
    $('#myItem').dataTable({
        "bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": 'Items/AjaxDataProvider',
        "sPaginationType": "full_numbers",
        "aoColumns": [
                                { "sName": "ID",
                                    "bSearchable": false,
                                    "bSortable": false,
                                    "bVisible": false
                                },
                    { "sName": "NAME" , "sWidth" : "20%" },
                    { "sName": "UOM", "sWidth": "7%" },
                    { "sName": "REMARKS", "sWidth" : "8%"},
                                { "sName": "BARCODE", "sWidth": "8%" },
                                { "sName": "WITH SERIAL", "sWidth": "10%" },
                                { "sName": "MODEL" }
             ]
    }).makeEditable({
        sUpdateURL: "/Items/UpdateData",
        sAddURL: "/Items/AddData",
        sDeleteURL: "/Items/DeleteData",
        aoColumns: [
        {  },
        {
            type: "select",
            onBlur: "submit",
            data: "{ ???? : ???? }"
        },
        {  },
        {  },
        {  },
        {  },
        {  },
        {  },
        {  },
        {  },
        {  } ]
    });
});
</code>```

I would like to insert into data area in makeEditable for second  which is for UOM from this result:

```<code>var selectData = from a in db.Table select new[] { Convert.ToString(m.ID), Convert.ToString(m.Name) };
</code>```

Anyone could give me a hand on solving this one?

Thanks a lot in advanced o/

答: I have finally manage to get the value for my selection list from SQL.  The steps are written at my blog at Negative Zero</p>

Title: JEditable using Select on MVC 3

Body:
I'm currently want to display a list of data using DataTables. And I want to be able to edit the record inline.  I could execute those with no problem.  The problem is, when I try to use drop down list(select) on one of the field for JEditable, that's when everything stuck to no where.

I would like to fetch the data from one of my table in MSSQL and dump it on data : "{ 'test' : 'test' }" for example.  but I cant find a way to do that. My JS knowledge is not that good.

Is there any way I could execute this? With this question, I include my current codes:
this is my initialization for Datatables and JEditable

$(document).ready(function () {
    $('#myItem').dataTable({
        "bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": 'Items/AjaxDataProvider',
        "sPaginationType": "full_numbers",
        "aoColumns": [
                                { "sName": "ID",
                                    "bSearchable": false,
                                    "bSortable": false,
                                    "bVisible": false
                                },
                    { "sName": "NAME" , "sWidth" : "20%" },
                    { "sName": "UOM", "sWidth": "7%" },
                    { "sName": "REMARKS", "sWidth" : "8%"},
                                { "sName": "BARCODE", "sWidth": "8%" },
                                { "sName": "WITH SERIAL", "sWidth": "10%" },
                                { "sName": "MODEL" }
             ]
    }).makeEditable({
        sUpdateURL: "/Items/UpdateData",
        sAddURL: "/Items/AddData",
        sDeleteURL: "/Items/DeleteData",
        aoColumns: [
        {  },
        {
            type: "select",
            onBlur: "submit",
            data: "{ ???? : ???? }"
        },
        {  },
        {  },
        {  },
        {  },
        {  },
        {  },
        {  },
        {  },
        {  } ]
    });
});

I would like to insert into data area in makeEditable for second  which is for UOM from this result:

var selectData = from a in db.Table select new[] { Convert.ToString(m.ID), Convert.ToString(m.Name) };

Anyone could give me a hand on solving this one?

Thanks a lot in advanced o/


问:
Extending File Comparer, GetHashCode method
I am trying to extend File Comparer, to substract root paths from path of files being compared. The problem is in GetHashCode() method as I have two different root paths (root_a and root_b). How to implement it properly that corresponding root pats are assigned to the right file?

```<code>class FileCompare : System.Collections.Generic.IEqualityComparer<System.IO.FileInfo>
{
    string m_root_a;
    string m_root_b;
    public FileCompare() { }
    public FileCompare(string root_a, string root_b)
    {
        m_root_a = root_a;
        m_root_b = root_b;
    }

    public bool Equals(System.IO.FileInfo f1, System.IO.FileInfo f2)
    {
        return (f1.FullName.Substring(m_root_a.Length) ==
            f2.FullName.Substring(m_root_b.Length) &&
            f1.Length == f2.Length);
    }

    public int GetHashCode(System.IO.FileInfo fi)
    {
        string s = $"{fi.FullName.Substring(m_root_a.Length)}{fi.Length}";
        return s.GetHashCode();
    }
}
</code>```

Code for testing the comparer:

```<code>System.IO.DirectoryInfo dir1 = new System.IO.DirectoryInfo("C:\\Dir Compare Tmp\\dir1\\");
System.IO.DirectoryInfo dir2 = new System.IO.DirectoryInfo("C:\\Dir Compare Tmp\\dir2\\");

IEnumerable<System.IO.FileInfo> list1 = dir1.GetFiles("*.*",
    System.IO.SearchOption.AllDirectories);
IEnumerable<System.IO.FileInfo> list2 = dir2.GetFiles("*.*",
    System.IO.SearchOption.AllDirectories);
FileCompare myFileCompare = new FileCompare("C:\\Dir Compare Tmp\\dir1\\",
    "C:\\Dir Compare Tmp\\dir2\\");

bool areIdentical = list1.SequenceEqual(list2, myFileCompare);

List<string> commonFilesList = new List<string>();
List<string> files1OnlyList = new List<string>();
List<string> files2OnlyList = new List<string>();

var queryCommonFiles = list1.Intersect(list2, myFileCompare);
var queryList1Only = (from file in list1 select file).Except(list2, myFileCompare);
var queryList2Only = (from file in list2 select file).Except(list1, myFileCompare);

foreach (var v in queryCommonFiles)
    commonFilesList.Add(v.FullName);

foreach (var v in queryList1Only)
    files1OnlyList.Add(v.FullName);

foreach (var v in queryList2Only)
    files2OnlyList.Add(v.FullName);
</code>```

Update: Unfortunately code does not work properly when I have different length of root paths e.g. second path C:\\Dir Compare Tmp\\dir2 - Copy\\. I get no files in commonFilesList (using GetHashCode implementation from the answer; fails Equals function). What would be solution for this, or should I use different approach to compare files? This will be used to compare large amount of files, therefore code latency is important.

答:
As your comparer is already storing both the root paths and only the files in those paths are expected to be passed to GetHashCode method, I hope the following implementation will get done what you want to achieve.

```<code>public int GetHashCode(System.IO.FileInfo fi)
    {
        if(fi.FullName.StartsWith(m_root_a))
            return fi.FullName.SubString(m_root_a.Length).GetHashCode();
        else if(fi.FullName.StartsWith(m_root_b))
            return fi.FullName.SubString(m_root_b.Length).GetHashCode();
        else
            throw Exception("Invalid File. This file is not a part of the directories compared.");
    }
</code>```

Update

Based on comment from @Rufus

as per the specified article at CA1065: Do not raise exceptions in unexpected locations
it states that

GetHashCode Methods: Object.GetHashCode and IEqualityComparer.GetHashCode(Object) method should "usually" not throw exceptions.

GetHashCode should always return a value. Otherwise, you can lose items in the hash table.

The versions of GetHashCode that take an argument can throw an ArgumentException. However, Object.GetHashCode should never throw
an exception.

BUT

If I am developing this application and to make sure that only files from specified directories are compared, I would definitely throw an Exception.

If a developer knowingly or unknowingly compares files from two different folders one or both of which were not used why initializing the object, then the file comparison is totally invalid.

Also, GetHashCode method returns an int while Windows allows uint (4x10^10) number of files. And if someone (who knows?) try to break the code, there will definitely be a hash collision and hence false matches; and I don't like to take such chances.

Instead I will be OK with losing the Hashtable, showing an error message to the user/developer and asking him/her to start again.

Body:
I am trying to extend File Comparer, to substract root paths from path of files being compared. The problem is in GetHashCode() method as I have two different root paths (root_a and root_b). How to implement it properly that corresponding root pats are assigned to the right file?

class FileCompare : System.Collections.Generic.IEqualityComparer<System.IO.FileInfo>
{
    string m_root_a;
    string m_root_b;
    public FileCompare() { }
    public FileCompare(string root_a, string root_b)
    {
        m_root_a = root_a;
        m_root_b = root_b;
    }

    public bool Equals(System.IO.FileInfo f1, System.IO.FileInfo f2)
    {
        return (f1.FullName.Substring(m_root_a.Length) ==
            f2.FullName.Substring(m_root_b.Length) &&
            f1.Length == f2.Length);
    }

    public int GetHashCode(System.IO.FileInfo fi)
    {
        string s = $"{fi.FullName.Substring(m_root_a.Length)}{fi.Length}";
        return s.GetHashCode();
    }
}

Code for testing the comparer:

System.IO.DirectoryInfo dir1 = new System.IO.DirectoryInfo("C:\\Dir Compare Tmp\\dir1\\");
System.IO.DirectoryInfo dir2 = new System.IO.DirectoryInfo("C:\\Dir Compare Tmp\\dir2\\");

IEnumerable<System.IO.FileInfo> list1 = dir1.GetFiles("*.*",
    System.IO.SearchOption.AllDirectories);
IEnumerable<System.IO.FileInfo> list2 = dir2.GetFiles("*.*",
    System.IO.SearchOption.AllDirectories);
FileCompare myFileCompare = new FileCompare("C:\\Dir Compare Tmp\\dir1\\",
    "C:\\Dir Compare Tmp\\dir2\\");

bool areIdentical = list1.SequenceEqual(list2, myFileCompare);

List<string> commonFilesList = new List<string>();
List<string> files1OnlyList = new List<string>();
List<string> files2OnlyList = new List<string>();

var queryCommonFiles = list1.Intersect(list2, myFileCompare);
var queryList1Only = (from file in list1 select file).Except(list2, myFileCompare);
var queryList2Only = (from file in list2 select file).Except(list1, myFileCompare);

foreach (var v in queryCommonFiles)
    commonFilesList.Add(v.FullName);

foreach (var v in queryList1Only)
    files1OnlyList.Add(v.FullName);

foreach (var v in queryList2Only)
    files2OnlyList.Add(v.FullName);

Update: Unfortunately code does not work properly when I have different length of root paths e.g. second path C:\\Dir Compare Tmp\\dir2 - Copy\\. I get no files in commonFilesList (using GetHashCode implementation from the answer; fails Equals function). What would be solution for this, or should I use different approach to compare files? This will be used to compare large amount of files, therefore code latency is important.

Body:
As your comparer is already storing both the root paths and only the files in those paths are expected to be passed to GetHashCode method, I hope the following implementation will get done what you want to achieve.

public int GetHashCode(System.IO.FileInfo fi)
    {
        if(fi.FullName.StartsWith(m_root_a))
            return fi.FullName.SubString(m_root_a.Length).GetHashCode();
        else if(fi.FullName.StartsWith(m_root_b))
            return fi.FullName.SubString(m_root_b.Length).GetHashCode();
        else
            throw Exception("Invalid File. This file is not a part of the directories compared.");
    }

Update

Based on comment from @Rufus

as per the specified article at CA1065: Do not raise exceptions in unexpected locations
it states that

GetHashCode Methods: Object.GetHashCode and IEqualityComparer.GetHashCode(Object) method should "usually" not throw exceptions.

GetHashCode should always return a value. Otherwise, you can lose items in the hash table.

The versions of GetHashCode that take an argument can throw an ArgumentException. However, Object.GetHashCode should never throw
an exception.

BUT

If I am developing this application and to make sure that only files from specified directories are compared, I would definitely throw an Exception.

If a developer knowingly or unknowingly compares files from two different folders one or both of which were not used why initializing the object, then the file comparison is totally invalid.

Also, GetHashCode method returns an int while Windows allows uint (4x10^10) number of files. And if someone (who knows?) try to break the code, there will definitely be a hash collision and hence false matches; and I don't like to take such chances.

Instead I will be OK with losing the Hashtable, showing an error message to the user/developer and asking him/her to start again.


问:
three.js import fails in Create React App
I have three.js installed in my Create React App project as:

"three": "^0.115.0",

When I try to import it in component by doing:

import * as THREE from "three"; then I get (abridged):

```<code>TypeError: attribute.onUploadCallback is not a function
createBuffer
node_modules/three/build/three.module.js:14471
  14468 | gl.bindBuffer( bufferType, buffer );
  14469 | gl.bufferData( bufferType, array, usage );
  14470 |
> 14471 | attribute.onUploadCallback();
        | ^  14472 |
  14473 | var type = 5126;
</code>```

If I create a file such as:

```<code>import * as THREE from "three";

window.THREE = THREE;

export default window.THREE;
</code>```

then I am able to successfully import from there.

I have no idea why I need to add it to window for it to work.

答: The error actually had to do with a related library that uses three.js called AMI.js.</p>

Body:
I have three.js installed in my Create React App project as:

"three": "^0.115.0",

When I try to import it in component by doing:

import * as THREE from "three"; then I get (abridged):

TypeError: attribute.onUploadCallback is not a function
createBuffer
node_modules/three/build/three.module.js:14471
  14468 | gl.bindBuffer( bufferType, buffer );
  14469 | gl.bufferData( bufferType, array, usage );
  14470 |
> 14471 | attribute.onUploadCallback();
        | ^  14472 |
  14473 | var type = 5126;

If I create a file such as:

import * as THREE from "three";

window.THREE = THREE;

export default window.THREE;

then I am able to successfully import from there.

I have no idea why I need to add it to window for it to work.


答:
Let us do </p>

```<code>df.doc_no=df.doc_no.astype(str)
s=df.groupby(['col1','col2','col3']).doc_no.agg(['count',','.join]).reset_index()
s
  col1 col2 col3  count   join
0    a    x    f      3  0,1,5
1    b    x    g      1      2
2    b    y    g      1      3
3    c    x    t      1      3
4    c    y    t      1      4
5    d    x    t      2    5,6
</code>```

Title: Pandas groupby concat ungrouped column into comma separated string

Body:
Let us do

df.doc_no=df.doc_no.astype(str)
s=df.groupby(['col1','col2','col3']).doc_no.agg(['count',','.join]).reset_index()
s
  col1 col2 col3  count   join
0    a    x    f      3  0,1,5
1    b    x    g      1      2
2    b    y    g      1      3
3    c    x    t      1      3
4    c    y    t      1      4
5    d    x    t      2    5,6


问:
how to call and echo a value from my database for a a certain user using username to identify the user
I have a table named users on my database which is suppose to hold balance in BTC and Cash in two of its rows
I have a php file which i have used to echo the value for each user using the user's username to identify the particular user, but for some reason the echoed data contains the whole row for BTC and Cash value instead of identifying the user using the username and displaying only the value in the column for BTC and Cash where it suppose to display the balance on my website.
So what i am basically looking for is the code to call the data from my database and using username to identify user, display the value for the user.

This is the html where it suppose to display the user's balance on my website

```<code><!doctype html>
<html>
<div class="logged-user-w text-center avatar-inline">
        <div class="logged-user-info-w">
    <div class="logged-user-name">
        <a class="text-primary" href="profile.php"><?php echo $_SESSION['username']; ?></a>

    </div>
//BTC balance//
    <div class="logged-user-role">
            <a class="text-grey" href="wallet.php"><?php include('new.php')?></a>
    </div>
//Cash balance//
    <div class="logged-user-role">
            <a class="text-grey" href="cashwallet.php"><?php include('new.php')?></a>
     </div>

</div>
</html>
</code>```

hare is the php (new.php) which is suppose to get the values from my database and echo it

```<code><?php

      // Server credentials
$servername = "";
$username = "";
$password = "";
$dbname = "";

// Creating mysql connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Checking mysql connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// Writing a mysql query to retrieve data
$sql = "SELECT * FROM users bitcoin, cash";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // Show each data returned by mysql
  while($row = $result->fetch_assoc()) {
?>

    <!-- USING HTML HERE : Here I am using php within html tags -->
    <p> <?php echo $row["bitcoin"]; ?></p>
    <p> <?php echo $row["cash"]; ?></p>
<?php
  }
} else {
  echo "0 results";
}

// Closing mysql connection
$conn->close();
?>
</code>```

答:
As stated by Kunal Raut, change your sql statement, but if you want to select the data based on the username, then use the following.

```<code>$sql = "SELECT bitcoin, cash FROM users WHERE username=$_SESSION[‘USERNAME’]”
</code>```

Or use the user id.

```<code>$sql = "SELECT bitcoin, cast FROM users WHERE userid= $_SESSION[‘USERID’]
</code>```

In both examples, you would need to change the field name to match what you used in the database to hold either the username or the user id.

Body:
I have a table named users on my database which is suppose to hold balance in BTC and Cash in two of its rows
I have a php file which i have used to echo the value for each user using the user's username to identify the particular user, but for some reason the echoed data contains the whole row for BTC and Cash value instead of identifying the user using the username and displaying only the value in the column for BTC and Cash where it suppose to display the balance on my website.
So what i am basically looking for is the code to call the data from my database and using username to identify user, display the value for the user.

This is the html where it suppose to display the user's balance on my website

<!doctype html>

        <?php echo $_SESSION['username']; ?>

//BTC balance//

            <?php include('new.php')?>

//Cash balance//

            <?php include('new.php')?>

hare is the php (new.php) which is suppose to get the values from my database and echo it

<?php

      // Server credentials
$servername = "";
$username = "";
$password = "";
$dbname = "";

// Creating mysql connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Checking mysql connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// Writing a mysql query to retrieve data
$sql = "SELECT * FROM users bitcoin, cash";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // Show each data returned by mysql
  while($row = $result->fetch_assoc()) {
?>

 <?php echo $row["bitcoin"]; ?>

 <?php echo $row["cash"]; ?>

<?php
  }
} else {
  echo "0 results";
}

// Closing mysql connection
$conn->close();
?>

Body:
As stated by Kunal Raut, change your sql statement, but if you want to select the data based on the username, then use the following.

$sql = "SELECT bitcoin, cash FROM users WHERE username=$_SESSION[‘USERNAME’]”

Or use the user id.

$sql = "SELECT bitcoin, cast FROM users WHERE userid= $_SESSION[‘USERID’]

In both examples, you would need to change the field name to match what you used in the database to hold either the username or the user id.


问:
Python recursion to split string by sliding window
Recently, I face an interesting coding task that involves splitting a string multiple permutations with a given K-limit size.

For example:

```<code>s = "iamfoobar"
k = 4  # the max number of the items on a list after the split
</code>```

The s can split into the following combinations

```<code>[
    ["i", "a", "m", "foobar"],
    ["ia", "m", "f", "oobar"],
    ["iam", "f", "o", "obar"]
# etc
]
</code>```

I tried to figure out how to do that with a quick recursively function, but I cannot get it to work.

I have try this out, but didn't seem to work

```<code>def sliding(s, k):
    if len(s) < k:
        return []
    else:
        for i in range(0, k):
            return [s[i:i+1]] + sliding(s[i+1:len(s) - i], k)

print(sliding("iamfoobar", 4))

</code>```

And only got this

```<code>['i', 'a', 'm', 'f', 'o', 'o']
</code>```

答:
Your first main problem is that although you use a loop, you immediately return a single list. So no matter how much you fix everything around, your output will never match what you expect as it will be.... a single list.

Second, on the recursive call you start with s[i:i+1] but according to your example you want all prefixes, so something like s[:i] is more suitable.

Additionaly, in the recursive call you never reduce k which is the natural recursive step.

Lastly, your stop condition seems wrong also. As above, if the natural step is reducing k, the natural stop would be if k == 1 then return [[s]]. This is because the only way to split the string to 1 part is the string itself...

The important thing is to keep in mind your final output format and think how that can work in your step. In this case you want to return a list of all possible permutations as lists. So in case of k == 1, you simply return a list of a single list of the string.

Now as the step, you want to take a different prefix each time, and add to it all permutations from the call of the rest of the string with k-1. All in all the code can be something like this:

def splt(s, k):
    if k == 1:  # base sace - stop condition
        return [[s]]

    res = []
    # loop over all prefixes
    for i in range(1, len(s)-k+2):
        for tmp in splt(s[i:], k-1):
            # add to prefix all permutations of k-1 parts of the rest of s
            res.append([s[:i]] + tmp)
    return res
```

<p>You can test it on some inputs and see how it works.</p>

<hr>

<p>If you are not restricted to recursion, another approach is to use <code>itertools.combinations</code>. You can use that to create all combinations of indexes inside the string to split it into <code>k</code> parts, and then simply concatenate those parts and put them in a list. A raw version is something like:</p>

<pre class="lang-py prettyprint-override"><code>from itertools import combinations

def splt(s, k):
    res = []
    for indexes in combinations(range(1, len(s)), k-1):
        indexes = [0] + list(indexes) + [len(s)] # add the edges to k-1 indexes to create k parts
        res.append([s[start:end] for start, end in zip(indexes[:-1], indexes[1:])]) # concatenate the k parts

    return res
</code>```

Body:
Recently, I face an interesting coding task that involves splitting a string multiple permutations with a given K-limit size.

For example:

s = "iamfoobar"
k = 4  # the max number of the items on a list after the split

The s can split into the following combinations

[
    ["i", "a", "m", "foobar"],
    ["ia", "m", "f", "oobar"],
    ["iam", "f", "o", "obar"]
# etc
]

I tried to figure out how to do that with a quick recursively function, but I cannot get it to work.

I have try this out, but didn't seem to work

def sliding(s, k):
    if len(s) < k:
        return []
    else:
        for i in range(0, k):
            return [s[i:i+1]] + sliding(s[i+1:len(s) - i], k)

print(sliding("iamfoobar", 4))

And only got this

['i', 'a', 'm', 'f', 'o', 'o']

Body:
Your first main problem is that although you use a loop, you immediately return a single list. So no matter how much you fix everything around, your output will never match what you expect as it will be.... a single list.

Second, on the recursive call you start with s[i:i+1] but according to your example you want all prefixes, so something like s[:i] is more suitable.

Additionaly, in the recursive call you never reduce k which is the natural recursive step.

Lastly, your stop condition seems wrong also. As above, if the natural step is reducing k, the natural stop would be if k == 1 then return [[s]]. This is because the only way to split the string to 1 part is the string itself...

The important thing is to keep in mind your final output format and think how that can work in your step. In this case you want to return a list of all possible permutations as lists. So in case of k == 1, you simply return a list of a single list of the string.

Now as the step, you want to take a different prefix each time, and add to it all permutations from the call of the rest of the string with k-1. All in all the code can be something like this:

def splt(s, k):
    if k == 1:  # base sace - stop condition
        return [[s]]

    res = []
    # loop over all prefixes
    for i in range(1, len(s)-k+2):
        for tmp in splt(s[i:], k-1):
            # add to prefix all permutations of k-1 parts of the rest of s
            res.append([s[:i]] + tmp)
    return res

You can test it on some inputs and see how it works.

If you are not restricted to recursion, another approach is to use itertools.combinations. You can use that to create all combinations of indexes inside the string to split it into k parts, and then simply concatenate those parts and put them in a list. A raw version is something like:

from itertools import combinations

def splt(s, k):
    res = []
    for indexes in combinations(range(1, len(s)), k-1):
        indexes = [0] + list(indexes) + [len(s)] # add the edges to k-1 indexes to create k parts
        res.append([s[start:end] for start, end in zip(indexes[:-1], indexes[1:])]) # concatenate the k parts

    return res


问:
Show array with variable in Symfony
In my symfony project, I pass from the Controller a variable called 'button'.

In this case 'button' has the value 'content' but this is not always.

I need it to display the content of phrase.content in the '.html.twig' file but I can't.

index.html.twig:

button = 'content'

```<code>{% for frase in frases %}

    <tr>
        <th scope="row">{{ frase.id }}</th>
        <td>{{ frase. ~ button }}</td>
    </tr>

{% endfor %}
</code>```

I have tried like this but it gives me the following error:

```<code>Expected name or number. (500 Internal Server Error)
</code>```

----EDIT----

If I put frase.content directly it does, but if I put frase[button], it gives an error

```<code>Impossible to access a key" content"on an object of class" App \ Entity \ Frase"
that does not implement ArrayAccess interface.
</code>```

答:
frase. expects something after the dot. A dot like this in twig is kind of like 's: In the table header you ask for frase's id. In the table definition (td) element, twig essentially thinks:

frase's " ~ button"?? I was expecting a property!

If button contains the name of the property you wish to show, you can use:

```<code>frase[button]
</code>```

In that case, if button is "content", twig will read it as

frase's content

PS: did you mean {% for phrase in phrases %}?

Title: Show array with variable in Symfony

Body:
In my symfony project, I pass from the Controller a variable called 'button'.

In this case 'button' has the value 'content' but this is not always.

I need it to display the content of phrase.content in the '.html.twig' file but I can't.

index.html.twig:

button = 'content'

{% for frase in frases %}

        {{ frase.id }}
        {{ frase. ~ button }}

{% endfor %}

I have tried like this but it gives me the following error:

Expected name or number. (500 Internal Server Error)

----EDIT----

If I put frase.content directly it does, but if I put frase[button], it gives an error

Impossible to access a key" content"on an object of class" App \ Entity \ Frase"
that does not implement ArrayAccess interface.

Body:
frase. expects something after the dot. A dot like this in twig is kind of like 's: In the table header you ask for frase's id. In the table definition (td) element, twig essentially thinks:

frase's " ~ button"?? I was expecting a property!

If button contains the name of the property you wish to show, you can use:

frase[button]

In that case, if button is "content", twig will read it as

frase's content

PS: did you mean {% for phrase in phrases %}?


问:
How to find Version of Qt?
How do I know which version of Qt I am using? When I open Qt Creator it shows "Welcome to Qt Creator 2.3". In the build setting, however, it shows Qt Version 4.7.1.</p>

答:
For qt4 :

QT_SELECT=4 qmake -v

for qt5 :

QT_SELECT=5 qmake -v

Title: How to find Version of Qt?


问:
How can I compile Python 3.6.2 on macOS with openSSL from homebrew?
I'm trying to compile Python 3.6.2 on macOS 10.11 according to the instructions on https://bugs.python.org/issue29095.

I've used homebrew to install openSSL to the standard location and then added LDFLAGS, CFLAGS, and CPPFLAGS to my env:

```<code>$ printenv | grep FLAGS
LDFLAGS=/usr/local/Cellar/openssl/1.0.2l/lib/
CFLAGS=-I/usr/local/Cellar/openssl/1.0.2l/include/openssl
CPPFLAGS=-I/usr/local/Cellar/openssl/1.0.2l/include/openssl
</code>```

Then in that same shell, I compile Python to the custom location required for my use case:

```<code>$ sudo ./configure --prefix=/oebuild/python/python-3.6.1
$ sudo make
$ sudo make install
</code>```

However, the SSL module doesn't get built. The build log says this:

Python build finished successfully!
  The necessary bits to build these optional modules were not found:
  _gdbm                 _ssl                  ossaudiodev

  spwd

  To find the necessary bits, look in setup.py in detect_modules() for the module's name.

答:
Been struggling with building from pyenv all day so figured I'd contribute the method for doing it in 2020:

```<code>brew install rbenv/tap/openssl@1.0
PYTHON_BUILD_HOMEBREW_OPENSSL_FORMULA=openssl@1.0 pyenv install 3.6.2
</code>```

or in my case, 3.4.10 (what I tested this with)

I know this question isn't for pyenv specifically but I found this thread looking for help with pyenv and I'm sure others have too.

Note that this version of openssl is (currently) 1.0.2t

Body:
I'm trying to compile Python 3.6.2 on macOS 10.11 according to the instructions on https://bugs.python.org/issue29095.

I've used homebrew to install openSSL to the standard location and then added LDFLAGS, CFLAGS, and CPPFLAGS to my env:

$ printenv | grep FLAGS
LDFLAGS=/usr/local/Cellar/openssl/1.0.2l/lib/
CFLAGS=-I/usr/local/Cellar/openssl/1.0.2l/include/openssl
CPPFLAGS=-I/usr/local/Cellar/openssl/1.0.2l/include/openssl

Then in that same shell, I compile Python to the custom location required for my use case:

$ sudo ./configure --prefix=/oebuild/python/python-3.6.1
$ sudo make
$ sudo make install

However, the SSL module doesn't get built. The build log says this:

Python build finished successfully!
  The necessary bits to build these optional modules were not found:
  _gdbm                 _ssl                  ossaudiodev

  spwd

  To find the necessary bits, look in setup.py in detect_modules() for the module's name.

Body:
Been struggling with building from pyenv all day so figured I'd contribute the method for doing it in 2020:

brew install rbenv/tap/openssl@1.0
PYTHON_BUILD_HOMEBREW_OPENSSL_FORMULA=openssl@1.0 pyenv install 3.6.2

or in my case, 3.4.10 (what I tested this with)

I know this question isn't for pyenv specifically but I found this thread looking for help with pyenv and I'm sure others have too.

Note that this version of openssl is (currently) 1.0.2t


问:
Potentially long loop and declaring variables inside
I've recently written a dynamic program that calculates the similarity (modified edit distance) between two sequences of DNA strands (can be lengthy).

My code is like (not actual code since its an assignment):

```<code>while(!file.eof){
   string line;
   int sizeY, sizeX;

   //get first strand
   getline(db, line)

   //second strand
   getline(db, line)

   double ** ary = new double[sizeY];
   //loop to initialize array

   for(i to sizeY)
   {
      for(i to sizex)
      {
            pair<string,string> p,d;
            p.first = "A";
            p.second = "T";
            d.first = "G";
            d.second = "C";
            //do some comparisons
      }
   }
}
</code>```

The code above will take approximately 40 minutes to complete on a file with ~2400 lines.
If I move the pair p,d and assignments outside the nested for-loop and run the exact same file, it will complete in about ~1 minute.

I've read in other threads that the performance is pretty much the same. I've also compiled it with -O2.

Why is the code above so much slower?

答:
In a compiled language with a good compiler (that does at least mediocre optimization) having variables declared inside a loop is never going to be a "loser" and often (especially for compilers with only modest optimization) will be a "winner".

With interpreted languages it's likely to be different, though.  Each time through the loop the interpreter will need to allocate the variable locations, and that could be expensive.

You could also have a "loser" situation with a poorly-designed compiled environment where allocating variables on the stack is expensive.

Though with any of these scenarios I'd be at a loss to explain a 40:1 difference.  I suspect that the omitted code may contain some important clues.

[Ah, on re-reading (and possibly on the poster's re-editing) I see that it's not simply variable DECLARATION, but OBJECT creation that's being moved outside of the loop.]

Body:
I've recently written a dynamic program that calculates the similarity (modified edit distance) between two sequences of DNA strands (can be lengthy).

My code is like (not actual code since its an assignment):

while(!file.eof){
   string line;
   int sizeY, sizeX;

   //get first strand
   getline(db, line)

   //second strand
   getline(db, line)

   double ** ary = new double[sizeY];
   //loop to initialize array

   for(i to sizeY)
   {
      for(i to sizex)
      {
            pair<string,string> p,d;
            p.first = "A";
            p.second = "T";
            d.first = "G";
            d.second = "C";
            //do some comparisons
      }
   }
}

The code above will take approximately 40 minutes to complete on a file with ~2400 lines.
If I move the pair p,d and assignments outside the nested for-loop and run the exact same file, it will complete in about ~1 minute.

I've read in other threads that the performance is pretty much the same. I've also compiled it with -O2.

Why is the code above so much slower?


问:
Adding to ngnix configuration using .ebextensions
I'm trying to add two simple things to nginx.conf which work fine until I deploy a new version on ELB, which is expected, so I know I need to use .ebextensions to do this but I either get an error saying "null values are not allowed in templates" or it just doesn't work.

This is my file which is in /.ebextensions/custom.config

```<code>files:
    "/etc/nginx/conf.d/000_my_config.conf":
    content: |
        client_max_body_size 100M;
        server {
            location / {
                index index.php index.html index.htm;
                try_files $uri $uri/ /index.php?$args;
            }
        }
</code>```

Simply trying to change the max upload size and adding the location info in to work with Wordpress

答:
There are indentation issues. it should be (note content):

```<code>files:
    "/etc/nginx/conf.d/000_my_config.conf":
        content: |
            client_max_body_size 100M;
            server {
                location / {
                    index index.php index.html index.htm;
                    try_files $uri $uri/ /index.php?$args;
                }
            }
</code>```

For form of the files, check here.

There could be other reasons why it fails, can't tell from the short question. But the indentation is definitely one of the reasons you have problems though.

Body:
I'm trying to add two simple things to nginx.conf which work fine until I deploy a new version on ELB, which is expected, so I know I need to use .ebextensions to do this but I either get an error saying "null values are not allowed in templates" or it just doesn't work.

This is my file which is in /.ebextensions/custom.config

files:
    "/etc/nginx/conf.d/000_my_config.conf":
    content: |
        client_max_body_size 100M;
        server {
            location / {
                index index.php index.html index.htm;
                try_files $uri $uri/ /index.php?$args;
            }
        }

Simply trying to change the max upload size and adding the location info in to work with Wordpress

Body:
There are indentation issues. it should be (note content):

files:
    "/etc/nginx/conf.d/000_my_config.conf":
        content: |
            client_max_body_size 100M;
            server {
                location / {
                    index index.php index.html index.htm;
                    try_files $uri $uri/ /index.php?$args;
                }
            }

For form of the files, check here.

There could be other reasons why it fails, can't tell from the short question. But the indentation is definitely one of the reasons you have problems though.


问:
How to look up logical partition count and size in Cosmos DB
In Cosmos DB, is it possible to see how many logical partitions my database has created and the current fill capacity of each partition? I'd like to know how evenly my partitioning strategy is dividing data. Also, I'd like to prepare for data re-distribution before I hit the 20GB limit on a hot partition. </p>

答:
Azure monitor for Cosmos DB. Check out the metrics.

https://learn.microsoft.com/en-us/azure/cosmos-db/use-metrics


问:
H1 element can't be centered
I want to center h1 next to my img but I can't because of img's padding https://prnt.sc/sqdd73 it's what I want any soltuion?

Gori News

```

<pre class="lang-css prettyprint-override"><code>header{
  width:100%;
  max-width: 1800px;
  height:99px;
  background:#FFF;
  margin:0 auto;
  background: #FFFFFF;
  box-shadow: 0px 4px 5px rgba(0, 0, 0, 0.13);
  border-radius: 14px;
}
header h1{
  font-family: Ropa Sans;
  font-style: normal;
  font-weight: normal;
  font-size: 70px;
  line-height: 75px;
  /* identical to box height */
  color: #212121;
  text-shadow: 2px 4px 4px rgba(0, 0, 0, 0.25);
  display: inline-block;
}
header img{
  margin:12px;
}
</code>```

答:
You should use flex:

header {
  background: #FFF;
  margin: 0 auto;
  background: #FFFFFF;
  box-shadow: 0px 4px 5px rgba(0, 0, 0, 0.13);
  border-radius: 14px;
  padding: 12px 24px;
}

.logo {
  display: flex;
  align-items: center;
}

header h1 {
  font-family: Ropa Sans;
  font-style: normal;
  font-weight: normal;
  font-size: 70px;
  line-height: 75px;
  /* identical to box height */
  color: #212121;
  text-shadow: 2px 4px 4px rgba(0, 0, 0, 0.25);
  display: inline-block;
  margin-left: 24px
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <header>
   <div class="logo">
     <img src="https://www.placecage.com/128/128" alt="Gori News | LOGO">
     <h1>Gori News</h1>
   </div>
 </header></code>```

Title: H1 element can't be centered

Body:
I want to center h1 next to my img but I can't because of img's padding https://prnt.sc/sqdd73 it's what I want any soltuion?

Gori News

header{
  width:100%;
  max-width: 1800px;
  height:99px;
  background:#FFF;
  margin:0 auto;
  background: #FFFFFF;
  box-shadow: 0px 4px 5px rgba(0, 0, 0, 0.13);
  border-radius: 14px;
}
header h1{
  font-family: Ropa Sans;
  font-style: normal;
  font-weight: normal;
  font-size: 70px;
  line-height: 75px;
  /* identical to box height */
  color: #212121;
  text-shadow: 2px 4px 4px rgba(0, 0, 0, 0.25);
  display: inline-block;
}
header img{
  margin:12px;
}

Body:
You should use flex:

header {
  background: #FFF;
  margin: 0 auto;
  background: #FFFFFF;
  box-shadow: 0px 4px 5px rgba(0, 0, 0, 0.13);
  border-radius: 14px;
  padding: 12px 24px;
}

.logo {
  display: flex;
  align-items: center;
}

header h1 {
  font-family: Ropa Sans;
  font-style: normal;
  font-weight: normal;
  font-size: 70px;
  line-height: 75px;
  /* identical to box height */
  color: #212121;
  text-shadow: 2px 4px 4px rgba(0, 0, 0, 0.25);
  display: inline-block;
  margin-left: 24px
}

 <header>
   <div class="logo">
     <img src="https://www.placecage.com/128/128" alt="Gori News | LOGO">
     <h1>Gori News</h1>
   </div>
 </header>


问:
ImportError: No module named selenium using import selenium even after installing Selenium in Python
I am trying to run tests with selenium in python, but it can not be recognized.

I have tried uninstalling with pip uninstall selenium and reinstalling, and it has not worked.

When i run import selenium i get this error:

```<code>import selenium
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named selenium
</code>```

But, when I run pip install selenium, I get:

```<code>Requirement already satisfied: selenium in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (3.141.0)
Requirement already satisfied: urllib3 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from selenium) (1.25.9)
</code>```

I am not sure if Selenium is just in the wrong place on my machine so it can not be recognized, or what is going on.

Thanks

答:
This error message...

```<code>import selenium

Traceback (most recent call last): File "", line 1, in ImportError: No module named selenium
</code>```

...implies that there was an error while invoking the Selenium module.

Analysis

On executing the line of code:

```<code>pip install selenium
</code>```

As you are seeing the message:

```<code>Requirement already satisfied: selenium in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (3.141.0)
Requirement already satisfied: urllib3 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from selenium) (1.25.9)
</code>```

implies that Selenium is already installed in your system.

Solution

Presumably, instead of using:

```<code>import selenium
</code>```

You need to use:

```<code>from selenium import webdriver
</code>```

Reference

You can find a relevant detailed discussion in:

Python : no module named selenium

Body:
I am trying to run tests with selenium in python, but it can not be recognized.

I have tried uninstalling with pip uninstall selenium and reinstalling, and it has not worked.

When i run import selenium i get this error:

import selenium
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named selenium

But, when I run pip install selenium, I get:

Requirement already satisfied: selenium in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (3.141.0)
Requirement already satisfied: urllib3 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from selenium) (1.25.9)

I am not sure if Selenium is just in the wrong place on my machine so it can not be recognized, or what is going on.

Thanks

Body:
This error message...

import selenium

Traceback (most recent call last): File "", line 1, in ImportError: No module named selenium

...implies that there was an error while invoking the Selenium module.

Analysis

On executing the line of code:

pip install selenium

As you are seeing the message:

Requirement already satisfied: selenium in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (3.141.0)
Requirement already satisfied: urllib3 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from selenium) (1.25.9)

implies that Selenium is already installed in your system.

Solution

Presumably, instead of using:

import selenium

You need to use:

from selenium import webdriver

Reference

You can find a relevant detailed discussion in:

Python : no module named selenium


问:
How to determine which eclipse plugins are contributing to menus and toolbars and stop them
I am creating an RCP app which uses a host of third-party plugins. Some of these plugins contribute menus, menu items, and toolbar buttons that I do not wish to display. How can I determine which plugins are contributing these menus, menu items, and toolbar buttons and how can I disable them from doing so?</p>

答:
To inspect details of menu, toolbar contributions etc.

Load the Eclipse Plug-in Spy in your RCP application by including the plug-in org.eclipse.pde.runtime

To inspect the current selection, press ALT-SHIFT-F1

To inspect menus, press ALT-SHIFT-F2 and then select the menu item

Use activities to remove the UI contribution. The "active action definition identifier" value provided by ALT-SHIFT-F2 is the one to use as the pattern in the activityPatternBinding specification. See this question for more info on removing unwanted UI contributions.

Note that when using activities to remove unwanted UI contributions, sometimes you will need to specify the UI contributions' plug-in id and sometimes you won't depending on the individual contribution.

NB: The Plug-in Registry view can be also used to find the IDs for contributions, although you'll have to do some searching.


问:
jQuery get relative click coords on an image in its actual dimensions
I have an image in my DOM and I want to get the mouse click coords relative to the image in its natural width and height not the one that fits the container. For example, when the mouse clicks on the image it gives back coords (50, 50) which are the actual click coords on the image in its actual dimensions.

Any idea how to attain this?

答:
I made a simple and easy script for you!

const getCoords = (e) => {

  e = (e||window.event);

  let absoluteCoords = {
    x: e.pageX - e.target.getBoundingClientRect().left,
    y: e.pageY - e.target.getBoundingClientRect().top
  }

  return {
    x: absoluteCoords.x / e.target.clientWidth * e.target.naturalWidth,
    y: absoluteCoords.y / e.target.clientHeight * e.target.naturalHeight
  };

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="https://wow.olympus.eu/webfile/img/1632/oly_testwow_stage.jpg?x=1024" onclick="console.log( getCoords(event) )"/></code>```

Body:
I made a simple and easy script for you!

const getCoords = (e) => {

  e = (e||window.event);

  let absoluteCoords = {
    x: e.pageX - e.target.getBoundingClientRect().left,
    y: e.pageY - e.target.getBoundingClientRect().top
  }

  return {
    x: absoluteCoords.x / e.target.clientWidth * e.target.naturalWidth,
    y: absoluteCoords.y / e.target.clientHeight * e.target.naturalHeight
  };

}

<img src="https://wow.olympus.eu/webfile/img/1632/oly_testwow_stage.jpg?x=1024" onclick="console.log( getCoords(event) )"/>


问:
Python output print problem for palindrome permutation
I want to see if a given string is a permutation of a palindrome or not. Here is the python solution. I am trying to test it for the following input example but I am getting error.

```<code>import re
class Solution(object):
    def isPalindrome(self, s):

        regex = re.compile('[^a-zA-Z0-9]')
        s=regex.sub('', lower(s))
        print(s)
        j=len(s)-1
        for i in range(0,len(s)/2):
            if s[i]==s[j]:
                j-=1
            else:
                return False

        return True

    # The word is civic , which is a palindrome. So it should return true.
    s = "vicic"

print(isPalindrome(s))
</code>```

I get this error : "NameError: name 'self' is not defined". How can I fix it and print the output?

答:
isPalindrome() as you have defined it here is associated with the object/class Solution.

Unlike a regular Python function your method is called on your solution object.

If you want to call it given your current structure you must first instantiate an instance of solution, create the string you want to test, and then call the method on the object:

```<code>sol = Solution() # instance of Solution
s = "vicic"
sol.isPalindrome(s) # False
</code>```

Also note that I took your string s out from where you had previously declared it as it was in the wrong scope.

In general it seems like your solution class may be a bit of overkill, part of the beauty of Python is its ability to write simple scripts, so you could rewrite isPalindrome() as a plain function and not a method.

Body:
I want to see if a given string is a permutation of a palindrome or not. Here is the python solution. I am trying to test it for the following input example but I am getting error.

import re
class Solution(object):
    def isPalindrome(self, s):

        regex = re.compile('[^a-zA-Z0-9]')
        s=regex.sub('', lower(s))
        print(s)
        j=len(s)-1
        for i in range(0,len(s)/2):
            if s[i]==s[j]:
                j-=1
            else:
                return False

        return True

    # The word is civic , which is a palindrome. So it should return true.
    s = "vicic"

print(isPalindrome(s))

I get this error : "NameError: name 'self' is not defined". How can I fix it and print the output?

Body:
isPalindrome() as you have defined it here is associated with the object/class Solution.

Unlike a regular Python function your method is called on your solution object.

If you want to call it given your current structure you must first instantiate an instance of solution, create the string you want to test, and then call the method on the object:

sol = Solution() # instance of Solution
s = "vicic"
sol.isPalindrome(s) # False

Also note that I took your string s out from where you had previously declared it as it was in the wrong scope.

In general it seems like your solution class may be a bit of overkill, part of the beauty of Python is its ability to write simple scripts, so you could rewrite isPalindrome() as a plain function and not a method.


问:
With Combine, how to deallocate the Subscription after a network request
If you use Combine for network requests with URLSession, then you need to save the Subscription (aka, the AnyCancellable) - otherwise it gets immediately deallocated, which cancels the network request. Later, when the network response has been processed, you want to deallocate the subscription, because keeping it around would be a waste of memory.

Below is some code that does this. It's kind of awkward, and it may not even be correct. I can imagine a race condition where network request could start and complete on another thread before sub is set to the non-nil value.

Is there a nicer way to do this?

```<code>class SomeThing {
    var subs = Set<AnyCancellable>()
    func sendNetworkRequest() {
        var request: URLRequest = ...
        var sub: AnyCancellable? = nil
        sub = URLSession.shared.dataTaskPublisher(for: request)
            .map(\.data)
            .decode(type: MyResponse.self, decoder: JSONDecoder())
            .sink(
                receiveCompletion: { completion in
                    self.subs.remove(sub!)
                },
                receiveValue: { response in ... }
            }
        subs.insert(sub!)
</code>```

答:
I call this situation a one-shot subscriber. The idea is that, because a data task publisher publishes only once, you know for a fact that it is safe to destroy the pipeline after you receive your single value and/or completion (error).

Here's a technique I like to use. First, here's the head of the pipeline:

```<code>let url = URL(string:"https://www.apeth.com/pep/manny.jpg")!
let pub : AnyPublisher<UIImage?,Never> =
    URLSession.shared.dataTaskPublisher(for: url)
        .map {$0.data}
        .replaceError(with: Data())
        .compactMap { UIImage(data:$0) }
        .receive(on: DispatchQueue.main)
        .eraseToAnyPublisher()
</code>```

Now comes the interesting part. Watch closely:

```<code>var cancellable: AnyCancellable? // 1
cancellable = pub.sink(receiveCompletion: {_ in // 2
    cancellable?.cancel() // 3
}) { image in
    self.imageView.image = image
}
</code>```

Do you see what I did there? Perhaps not, so I'll explain it:

First, I declare a local AnyCancellable variable; for reasons having to do with the rules of Swift syntax, this needs to be an Optional.

Then, I create my subscriber and set my AnyCancellable variable to that subscriber. Again, for reasons having to do with the rules of Swift syntax, my subscriber needs to be a Sink.

Finally, in the subscriber itself, I cancel the AnyCancellable when I receive the completion.

The cancellation in the third step actually does two things quite apart from calling cancel() — things having to do with memory management:

By referring to cancellable inside the asynchronous completion function of the Sink, I keep cancellable and the whole pipeline alive long enough for a value to arrive from the subscriber.

By cancelling cancellable, I permit the pipeline to go out of existence and prevent a retain cycle that would cause the surrounding view controller to leak.

Body:
If you use Combine for network requests with URLSession, then you need to save the Subscription (aka, the AnyCancellable) - otherwise it gets immediately deallocated, which cancels the network request. Later, when the network response has been processed, you want to deallocate the subscription, because keeping it around would be a waste of memory.

Below is some code that does this. It's kind of awkward, and it may not even be correct. I can imagine a race condition where network request could start and complete on another thread before sub is set to the non-nil value.

Is there a nicer way to do this?

class SomeThing {
    var subs = Set<AnyCancellable>()
    func sendNetworkRequest() {
        var request: URLRequest = ...
        var sub: AnyCancellable? = nil
        sub = URLSession.shared.dataTaskPublisher(for: request)
            .map(\.data)
            .decode(type: MyResponse.self, decoder: JSONDecoder())
            .sink(
                receiveCompletion: { completion in
                    self.subs.remove(sub!)
                },
                receiveValue: { response in ... }
            }
        subs.insert(sub!)

Body:
I call this situation a one-shot subscriber. The idea is that, because a data task publisher publishes only once, you know for a fact that it is safe to destroy the pipeline after you receive your single value and/or completion (error).

Here's a technique I like to use. First, here's the head of the pipeline:

let url = URL(string:"https://www.apeth.com/pep/manny.jpg")!
let pub : AnyPublisher<UIImage?,Never> =
    URLSession.shared.dataTaskPublisher(for: url)
        .map {$0.data}
        .replaceError(with: Data())
        .compactMap { UIImage(data:$0) }
        .receive(on: DispatchQueue.main)
        .eraseToAnyPublisher()

Now comes the interesting part. Watch closely:

var cancellable: AnyCancellable? // 1
cancellable = pub.sink(receiveCompletion: {_ in // 2
    cancellable?.cancel() // 3
}) { image in
    self.imageView.image = image
}

Do you see what I did there? Perhaps not, so I'll explain it:

First, I declare a local AnyCancellable variable; for reasons having to do with the rules of Swift syntax, this needs to be an Optional.

Then, I create my subscriber and set my AnyCancellable variable to that subscriber. Again, for reasons having to do with the rules of Swift syntax, my subscriber needs to be a Sink.

Finally, in the subscriber itself, I cancel the AnyCancellable when I receive the completion.

The cancellation in the third step actually does two things quite apart from calling cancel() — things having to do with memory management:

By referring to cancellable inside the asynchronous completion function of the Sink, I keep cancellable and the whole pipeline alive long enough for a value to arrive from the subscriber.

By cancelling cancellable, I permit the pipeline to go out of existence and prevent a retain cycle that would cause the surrounding view controller to leak.


问:
How to loop an object in React?
New to React and trying to loop Object attributes but React complains about Objects not being valid React children, can someone please give me some advice on how to resolve this problem? I've added createFragment but not completely sure where this needs to go or what approach I should take?

JS

```<code>var tifs = {1: 'Joe', 2: 'Jane'};
var tifOptions = Object.keys(tifs).forEach(function(key) {
    return <option value={key}>{tifs[key]}</option>
});
</code>```

Render function

```<code>render() {
        const model = this.props.model;

        let tifOptions = {};

        if(model.get('tifs')) {
            tifOptions = Object.keys(this.props.model.get('tifs')).forEach(function(key) {
                return <option value={key}>{this.props.model.get('tifs')[key]}</option>
            });
        }

        return (
            <div class={cellClasses}>

                    <div class="grid__col-5 text--center grid__col--bleed">
                        <h5 class="flush text--uppercase">TIF</h5>
                        <select id="tif" name="tif" onChange={this.handleChange}>
                            {tifOptions}
                        </select>
                    </div>

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

Error in console

```<code>If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object)
</code>```

答:
```<code>const tifOptions = [];

for (const [key, value] of Object.entries(tifs)) {
    tifOptions.push(<option value={key} key={key}>{value}</option>);
}

return (
   <select id="tif" name="tif" onChange={this.handleChange}>
      { tifOptions }
   </select>
)
</code>```

Title: How to loop an object in React?

Body:
New to React and trying to loop Object attributes but React complains about Objects not being valid React children, can someone please give me some advice on how to resolve this problem? I've added createFragment but not completely sure where this needs to go or what approach I should take?

JS

var tifs = {1: 'Joe', 2: 'Jane'};
var tifOptions = Object.keys(tifs).forEach(function(key) {
    return <option value={key}>{tifs[key]}</option>
});

Render function

render() {
        const model = this.props.model;

        let tifOptions = {};

        if(model.get('tifs')) {
            tifOptions = Object.keys(this.props.model.get('tifs')).forEach(function(key) {
                return <option value={key}>{this.props.model.get('tifs')[key]}</option>
            });
        }

        return (

TIF

                        <select id="tif" name="tif" onChange={this.handleChange}>
                            {tifOptions}
                        </select>

        );
    }

Error in console

If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object)


问:
What is the procedure to install StyleCop?
I am trying to install StyleCop, but I am unable to install it. After installation I couldn't see StyleCop in my code. If anyone find please help me regarding this.</p>

答: As you're using VS Express you won't see it, as VS Express only supports a limited number of plugins. You may be able to run it manually by hacking the solution file via MSBuild integration