问:
Why web3.eth.getAccounts().then(console.log) return empty array?
I got empty array after I tried to web3.eth.getAccounts().then(console.log);and also got a warning which is./node_modules/web3-eth-accounts/src/scrypt.js Critical dependency: the request of a dependency is an expression. In this project I first commanded create-react-app lottery_react and then all I changed in my lottery_react folder are modifying App.js with only one line web3.eth.getAccounts().then(console.log); and creating web3.js file. I can't find what's wrong in these file. Please help!

I've seen this and this but we all face different kinds of problem.

This is my App.js

```<code>import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';

import web3 from './web3';

class App extends Component {
  render(){
    web3.eth.getAccounts().then(console.log);
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
      </div>
    );
  }
}

export default App;
</code>```

This is my web3.js file

```<code>
import Web3 from 'web3';

const web3 = new Web3(window.web3.currentProvider);

export default web3;
</code>```

答:
It is very simple you just need to enable the Ethereum in the browser, you can do like this:
Just add await window.ethereum.enable();

```<code>     const getData = async () => {
        const web3 = new Web3(Web3.givenProvider);
        const network = await web3.eth.net.getNetworkType();
        await window.ethereum.enable();
        const accounts = await web3.eth.getAccounts();
        setAccount(accounts[0]);
        console.log("TCL: getData -> network", network);
        console.log("TCL: getData -> accounts", accounts);
      };
</code>```

Body:
I got empty array after I tried to web3.eth.getAccounts().then(console.log);and also got a warning which is./node_modules/web3-eth-accounts/src/scrypt.js Critical dependency: the request of a dependency is an expression. In this project I first commanded create-react-app lottery_react and then all I changed in my lottery_react folder are modifying App.js with only one line web3.eth.getAccounts().then(console.log); and creating web3.js file. I can't find what's wrong in these file. Please help!

I've seen this and this but we all face different kinds of problem.

This is my App.js

import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';

import web3 from './web3';

class App extends Component {
  render(){
    web3.eth.getAccounts().then(console.log);
    return (

            Edit src/App.js and save to reload.

            Learn React

    );
  }
}

export default App;

This is my web3.js file

import Web3 from 'web3';

const web3 = new Web3(window.web3.currentProvider);

export default web3;

Body:
It is very simple you just need to enable the Ethereum in the browser, you can do like this:
Just add await window.ethereum.enable();

     const getData = async () => {
        const web3 = new Web3(Web3.givenProvider);
        const network = await web3.eth.net.getNetworkType();
        await window.ethereum.enable();
        const accounts = await web3.eth.getAccounts();
        setAccount(accounts[0]);
        console.log("TCL: getData -> network", network);
        console.log("TCL: getData -> accounts", accounts);
      };


来源: stackexchange

问:
Compare current time to file date time last modified in Windows Batch File
I would like a command in a batch file to only execute if it has not been ran for the last 15 minutes. To achieve this I can create a "last_run" file to log the time last ran.

Where I am stuck is comparing the time last modified to the current time and taking action if the time last modified.

Here is my current code:

```<code>@echo off
set filename=last_run.txt
if not exist %filename% (
   rem NOT EXISTS, CREATE FILE THEN PRINT THE LIST
   echo.>"%filename%"
   GOTO PrintList
) else (
   rem FILE EXISTS, GET TIME LAST MODIFIED
   FOR %%? IN (%filename%) DO (set filetime=%%~t?)
   echo %filetime%
   rem IF TIME LAST MODIFIED > 15 MINS PRINT THE LIST
   if timediff??(%filetime%, current) > 15 mins {
      GOTO PrintList
   } else {
      GOTO End
   }
)

:PrintList
rem PRINT THE LIST
echo now print the list
rem WRITE TO THE FILE TO UPDATE TIME LAST MODIFIED
echo.>"%filename%"
GOTO End

:End
</code>```

答:
Besides the missing time calculation, your code has a delayed expansion problem. (My solution below doesn't need delayed expansion)

cmd is incredibly crude when it comes to date/time calculation (it can be done, but...).

Better use the help of another language (like PowerShell):

```<code>@echo off
setlocal
set "filename=last_run.txt"
set "minutes=15"
if not exist "%filename%" (
   break>"%filename%"
   goto :PrintList
)
for /f %%a in ('"powershell Test-Path %filename% -OlderThan (Get-Date).AddMinutes(-%minutes%)"') do set "older=%%a"
if "%older%" == "True" (
  echo %filename% is older than %minutes% minutes; print list
  break>"%filename%"
  goto :PrintList
) else (
  echo %filename% is younger than %minutes% minutes; exiting
  goto :eof
)
:PrintList
echo insert your payload here.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like a command in a batch file to only execute if it has not been ran for the last 15 minutes. To achieve this I can create a "last_run" file to log the time last ran.

Where I am stuck is comparing the time last modified to the current time and taking action if the time last modified.

Here is my current code:

@echo off
set filename=last_run.txt
if not exist %filename% (
   rem NOT EXISTS, CREATE FILE THEN PRINT THE LIST
   echo.>"%filename%"
   GOTO PrintList
) else (
   rem FILE EXISTS, GET TIME LAST MODIFIED
   FOR %%? IN (%filename%) DO (set filetime=%%~t?)
   echo %filetime%
   rem IF TIME LAST MODIFIED > 15 MINS PRINT THE LIST
   if timediff??(%filetime%, current) > 15 mins {
      GOTO PrintList
   } else {
      GOTO End
   }
)

:PrintList
rem PRINT THE LIST
echo now print the list
rem WRITE TO THE FILE TO UPDATE TIME LAST MODIFIED
echo.>"%filename%"
GOTO End

:End

Body:
Besides the missing time calculation, your code has a delayed expansion problem. (My solution below doesn't need delayed expansion)

cmd is incredibly crude when it comes to date/time calculation (it can be done, but...).

Better use the help of another language (like PowerShell):

@echo off
setlocal
set "filename=last_run.txt"
set "minutes=15"
if not exist "%filename%" (
   break>"%filename%"
   goto :PrintList
)
for /f %%a in ('"powershell Test-Path %filename% -OlderThan (Get-Date).AddMinutes(-%minutes%)"') do set "older=%%a"
if "%older%" == "True" (
  echo %filename% is older than %minutes% minutes; print list
  break>"%filename%"
  goto :PrintList
) else (
  echo %filename% is younger than %minutes% minutes; exiting
  goto :eof
)
:PrintList
echo insert your payload here.


问:
Switching 2 methods parameter(different type) to use overloading
I'm a High school student, I studied a little bit of Java by myself.
My teacher asked if you can write two methods with switched but same parameters. For example:

```<code>public void method (String arg1, int arg2){
}

public void method(int arg1, String arg2){
}
</code>```

I said yes, the teacher said that I don't know what overloading means, but I tested and it worked, and then she said "JDK has a bug" and she got mad at me.

I need a super and complete answer.

答: Overloading allows different methods to have the same name, but different signatures where the signature can differ by the number of input parameters, or type of input parameters, or order of input parameters.</p>

Body:
I'm a High school student, I studied a little bit of Java by myself.
My teacher asked if you can write two methods with switched but same parameters. For example:

public void method (String arg1, int arg2){
}

public void method(int arg1, String arg2){
}

I said yes, the teacher said that I don't know what overloading means, but I tested and it worked, and then she said "JDK has a bug" and she got mad at me.

I need a super and complete answer.


问:
How to create narrowed typescript interfaces from existing interface which has optional fields?
I have an interface with optional field(s) like this one:

interface Config {
  foo: Foo
  bar?: Bar
}
```

<p>In a function I check whether they are not <code>undefined</code>, then call another function: </p>

<pre class="lang-js prettyprint-override"><code>function doSomething(config: Config) {
  // ...
  if(config.bar) {
    const result = calculateSomethingUsingFooAndBar(config)
    // ...
  }
  // ...
}
</code>```

Of course inside the if's scope the bar is narrowed which means we know that it exists and is not optional anymore. So I want to call the function calculateSomethingUsingFooAndBar without defining a new interface just for making bar required, but telling the compiler that when this method is called it should already have bar. Also if I want to call the function from somewhere else, where the bar was not narrowed, that should cause a compile-time error, as we are not sure if bar was defined.

function calculateSomethingUsingFooAndBar(config: Narrowed<Config>) {
   // config.bar (and every other optional field) is defined here, we can use it.
}
```

Is there such a thing or a neat but not hacky workaround for this? I have checked the advanced typescript types but could not figure out if they can help me or not.

答:
You can use the Required<T> type for this. It makes all properties of T required.

See: https://www.typescriptlang.org/docs/handbook/utility-types.html#requiredt

Body:
I have an interface with optional field(s) like this one:

interface Config {
  foo: Foo
  bar?: Bar
}

In a function I check whether they are not undefined, then call another function:

function doSomething(config: Config) {
  // ...
  if(config.bar) {
    const result = calculateSomethingUsingFooAndBar(config)
    // ...
  }
  // ...
}

Of course inside the if's scope the bar is narrowed which means we know that it exists and is not optional anymore. So I want to call the function calculateSomethingUsingFooAndBar without defining a new interface just for making bar required, but telling the compiler that when this method is called it should already have bar. Also if I want to call the function from somewhere else, where the bar was not narrowed, that should cause a compile-time error, as we are not sure if bar was defined.

function calculateSomethingUsingFooAndBar(config: Narrowed<Config>) {
   // config.bar (and every other optional field) is defined here, we can use it.
}

Is there such a thing or a neat but not hacky workaround for this? I have checked the advanced typescript types but could not figure out if they can help me or not.


答:
If you are talking about methods on same class, it's possible in Java and is legit:

```<code>public class Test {

    public static void main(String[] args) {
        Test test = new Test();

    }

    public void method (String arg1, int arg2){
    }

    public void method(int arg1, String arg2){
    }
}
</code>```

This works because two methods have same name, but differnt type for parameters, so for Java there are two different methods.

Title: Switching 2 methods parameter(different type) to use overloading

Body:
If you are talking about methods on same class, it's possible in Java and is legit:

public class Test {

    public static void main(String[] args) {
        Test test = new Test();

    }

    public void method (String arg1, int arg2){
    }

    public void method(int arg1, String arg2){
    }
}

This works because two methods have same name, but differnt type for parameters, so for Java there are two different methods.


问:
Uncaught Reference Error in Duda Widget Builder. Html/JS
My code gives me the following error for the first function:

Uncaught ReferenceError: myFunction is not defined at HTMLButtonElement.onclick

I also get this error for the second function:

Uncaught ReferenceError: filterFunction is not defined at HTMLInputElement.onkeyup

I checked for answers and the most commonly given was "Select No wrap - bottom of  in the "Load type" dropdown in the JavaScript settings."

I cant select this since I'm using a Duda widget builder and no classic development environment.  Any ideas would be appreciated. Thanks a lot.

function myFunction() {
 document.getElementById("myDropdown").classList.toggle("show"); // Klicken zeigt bzw. verbirgt die Dropdown Liste
}

function filterFunction() {
  var input, filter, ul, li, a, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  div = document.getElementById("myDropdown");
  a = div.getElementsByTagName("a");
  for (i = 0; i  -1) {
      a[i].style.display = "";
    } else {
      a[i].style.display = "none";
    }
  }

  if (event.key === 'Enter') {
    console.log(ele.value);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="dropdown3">
  <button onclick="myFunction()" class="dropbtn">Bereich</button>
  <div id="myDropdown" class="dropdown-content">
    <input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
    Pflege
    Verwaltung
    Gastronomie
    Wäscherei
  </div>
</div></code>```

答:
The fix you've found only applies to code executed in a https://jsfiddle.net demo.

In your case you have two fixes you can use. The first is to make the two functions globally scoped. This is why the onX attributes can't find them currently, they're out of scope.

The other, and far better, approach, is to get rid of the onX attributes from your HTML entirely and use unobtrusive event handlers. Here's an example of how to do that:

document.querySelector('.dropbtn').addEventListener('click', function() {
  document.getElementById("myDropdown").classList.toggle("show");
})

document.querySelector('#myInput').addEventListener('keyup', function(e) {
  let filter = this.value.toUpperCase();
  let div = document.querySelector("#myDropdown");
  let a = div.getElementsByTagName("a");

  for (i = 0; i  -1) {
      a[i].style.display = "";
    } else {
      a[i].style.display = "none";
    }
  }

  if (e.key === 'Enter') {
    console.log(this.value);
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="dropdown3">
  <button class="dropbtn">Bereich</button>
  <div id="myDropdown" class="dropdown-content">
    <input type="text" placeholder="Search.." id="myInput" />
    Pflege
    Verwaltung
    Gastronomie
    Wäscherei
  </div>
</div></code>```

Body:
My code gives me the following error for the first function:

Uncaught ReferenceError: myFunction is not defined at HTMLButtonElement.onclick

I also get this error for the second function:

Uncaught ReferenceError: filterFunction is not defined at HTMLInputElement.onkeyup

I checked for answers and the most commonly given was "Select No wrap - bottom of  in the "Load type" dropdown in the JavaScript settings."

I cant select this since I'm using a Duda widget builder and no classic development environment.  Any ideas would be appreciated. Thanks a lot.

function myFunction() {
 document.getElementById("myDropdown").classList.toggle("show"); // Klicken zeigt bzw. verbirgt die Dropdown Liste
}

function filterFunction() {
  var input, filter, ul, li, a, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  div = document.getElementById("myDropdown");
  a = div.getElementsByTagName("a");
  for (i = 0; i  -1) {
      a[i].style.display = "";
    } else {
      a[i].style.display = "none";
    }
  }

  if (event.key === 'Enter') {
    console.log(ele.value);
  }
}

  <button onclick="myFunction()" class="dropbtn">Bereich</button>

    <input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
    Pflege
    Verwaltung
    Gastronomie
    Wäscherei

Body:
The fix you've found only applies to code executed in a https://jsfiddle.net demo.

In your case you have two fixes you can use. The first is to make the two functions globally scoped. This is why the onX attributes can't find them currently, they're out of scope.

The other, and far better, approach, is to get rid of the onX attributes from your HTML entirely and use unobtrusive event handlers. Here's an example of how to do that:

document.querySelector('.dropbtn').addEventListener('click', function() {
  document.getElementById("myDropdown").classList.toggle("show");
})

document.querySelector('#myInput').addEventListener('keyup', function(e) {
  let filter = this.value.toUpperCase();
  let div = document.querySelector("#myDropdown");
  let a = div.getElementsByTagName("a");

  for (i = 0; i < a.length; i++) {
    let txtValue = a[i].textContent || a[i].innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      a[i].style.display = "";
    } else {
      a[i].style.display = "none";
    }
  }

  if (e.key === 'Enter') {
    console.log(this.value);
  }
})

<div class="dropdown3">
  <button class="dropbtn">Bereich</button>
  <div id="myDropdown" class="dropdown-content">
    <input type="text" placeholder="Search.." id="myInput" />
    <a href="#pflege">Pflege</a>
    <a href="#verwaltung">Verwaltung</a>
    <a href="#gastro">Gastronomie</a>
    <a href="#wäsche">Wäscherei</a>
  </div>
</div>


问:
How to destructring nested object in js
```<code>let options = {
  size: {
    width: 100,
    height: 200
  },
  items: ["Cake", "Donut"],
  extra: true
};
// destructuring assignment split in multiple lines for clarity
let {
  size: { // put size here
    width,
    height
  },
  items: [item1, item2], // assign items here
  title = "Menu" // not present in the object (default value is used)
} = options;
console.log(title);  // Menu
</code>```

This is working fine, but when I want to get list of data from API it doesn't work with nested destructuring. However, I can show data by using && for example options && options.title  it's worked fine.

答: In order to destructure, you have to know the structure of the data that comes in. Maybe you can present your problem in a clear way by showing the structure of your api endpoint result </p>

Title: How to destructring nested object in js

Body:
let options = {
  size: {
    width: 100,
    height: 200
  },
  items: ["Cake", "Donut"],
  extra: true
};
// destructuring assignment split in multiple lines for clarity
let {
  size: { // put size here
    width,
    height
  },
  items: [item1, item2], // assign items here
  title = "Menu" // not present in the object (default value is used)
} = options;
console.log(title);  // Menu

This is working fine, but when I want to get list of data from API it doesn't work with nested destructuring. However, I can show data by using && for example options && options.title  it's worked fine.


问:
Install Redis-Commander as service on Ubuntu 19.04
I created my self a virtual machine with an Ubuntu 19.04 guest system running redis and redis commander.

I can access the redis commander via 8081 but need to start it manually everytime I start the VM.

How would I install the redis-commander as linux service? I would like to keep it directly installed in Ubuntu and not running in a docker container.

答:
Yes, you can. I had the same issue but on Centos 7. In /etc/systemd/system directory you should create .service file, for example, my-redis-commader.service. The content of file is like this:

```<code>[Unit]
Description=Redis Commander Activator
After=network.target

[Service]
WorkingDirectory=/usr/lib/node_modules/redis-commander/bin/
ExecStart=/usr/bin/node /usr/lib/node_modules/redis-commander/bin/redis-commander.js

[Install]
WantedBy=multi-user.target
</code>```

where

/usr/bin/node - node.js executable file

/usr/lib/node_modules/redis-commander/bin/redis-commander.js - is the file of node.js module, which run the web application - gui for redis server.

Then run:

```<code>systemctl enable my-redis-commander.service
systemctl start my-redis-commander.service
</code>```

Check status:

```<code>systemctl status my-redis-commander.service
</code>```

Body:
Yes, you can. I had the same issue but on Centos 7. In /etc/systemd/system directory you should create .service file, for example, my-redis-commader.service. The content of file is like this:

[Unit]
Description=Redis Commander Activator
After=network.target

[Service]
WorkingDirectory=/usr/lib/node_modules/redis-commander/bin/
ExecStart=/usr/bin/node /usr/lib/node_modules/redis-commander/bin/redis-commander.js

[Install]
WantedBy=multi-user.target

where

/usr/bin/node - node.js executable file

/usr/lib/node_modules/redis-commander/bin/redis-commander.js - is the file of node.js module, which run the web application - gui for redis server.

Then run:

systemctl enable my-redis-commander.service
systemctl start my-redis-commander.service

Check status:

systemctl status my-redis-commander.service


问:
Xcode 8 ios 10 Simulator , is it possible to send push notification to the simulator
My app uses Firebase. I am trying to send push notification to app running in simulator. When I run the app in iOS 10 Simulator, it successfully generates InstanceID token but shows warning that

notifications are not supported in the simulator.

I read somewhere on stackoverflow that it is possible to send push notification on iOS 10 simulator. Is it true?

答:
Now it is possible to receive a Push notification (with sound and badge count) in Simulator

click here
https://stackoverflow.com/a/60282092/2302313

ContentLicense: CC BY-SA 3.0


问:
Thymeleaf fragment: passing form field name as parameter
I'm trying to extract a form input as a page fragment in my Spring Boot + Thymeleaf application.

I'm doing something like this:

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>form controls</title>
</head>
<body>
<div class="form-group" th:fragment="text-input (fieldName, fieldLabel)">
    <label th:text="${fieldLabel}">label</label>
    <input th:field="*{${fieldName}}" type="text" class="form-control"/>
    <div th:if="${#fields.hasErrors('${fieldName}')}">
        <span th:errors="*{${fieldName}}" class="text-danger"></span>
    </div>
</div>
</body>
</html>
</code>```

And I'm using the fragment this way:

```<code><div th:replace="form-controls :: text-input (fieldName='firstName', fieldLabel='Name')">
</code>```

But I'm getting this error:

```<code>org.springframework.beans.NotReadablePropertyException: Invalid property '${fieldName}' of bean class [my.app.Dto]: Bean property '${fieldName}' is not readable or has an invalid getter method
</code>```

So the parameter fieldName is not resolved correctly...

Is there something wrong in my code? Is it possible to implement something similar to my fragment in Thymeleaf?

答:
The solution to my issue was: Thymeleaf expression preprocessing.

Preprocessing is an execution of the expressions done before the normal one that allows for modification of the expression that will eventually be executed.

So, to fix fieldName resolution I had to surround every ${fieldName} exp with a double underscore:

```<code><div class="form-group" th:fragment="text-input (fieldName, fieldLabel)">
    <label th:text="${fieldLabel}">label</label>
    <input th:field="*{__${fieldName}__}" type="text" class="form-control"/>
    <div th:if="${#fields.hasErrors(fieldName)}">
        <span th:errors="*{__${fieldName}__}" class="text-danger"></span>
    </div>
</div>
</code>```

Body:
I'm trying to extract a form input as a page fragment in my Spring Boot + Thymeleaf application.

I'm doing something like this:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>form controls</title>

    label
    <input th:field="*{${fieldName}}" type="text" class="form-control"/>

And I'm using the fragment this way:

But I'm getting this error:

org.springframework.beans.NotReadablePropertyException: Invalid property '${fieldName}' of bean class [my.app.Dto]: Bean property '${fieldName}' is not readable or has an invalid getter method

So the parameter fieldName is not resolved correctly...

Is there something wrong in my code? Is it possible to implement something similar to my fragment in Thymeleaf?

Body:
The solution to my issue was: Thymeleaf expression preprocessing.

Preprocessing is an execution of the expressions done before the normal one that allows for modification of the expression that will eventually be executed.

So, to fix fieldName resolution I had to surround every ${fieldName} exp with a double underscore:

<div class="form-group" th:fragment="text-input (fieldName, fieldLabel)">
    <label th:text="${fieldLabel}">label</label>
    <input th:field="*{__${fieldName}__}" type="text" class="form-control"/>
    <div th:if="${#fields.hasErrors(fieldName)}">
        <span th:errors="*{__${fieldName}__}" class="text-danger"></span>
    </div>
</div>


问:
How do I print an item from a multidemnsional array in Smarty and subsequently loop through it?
I am very new to Smarty and PHP in general and am quite struggling with multidimensional arrays. I have a multidimensional array called $tag_groups. When I print the array with {$tag_groups|@debug_print_var} I get the following output:

```<code>Array (2)
0 => Array (2)
  tags => Array (4)
    0 => Array (8)
      id => "10"
      name => "Os coxa"
      url_name => "axial_os_coxa"
      lastmodified => "2020-02-18 10:42:13"
      counter => 76
      level => 3
      group => "Axial"
      URL => "index.php?/tags/10-axial_os_coxa"
    1 => Array (8)
      id => "12"
      name => "Rib"
      url_name => "axial_rib"
      lastmodified => "2020-02-18 10:42:13"
      counter => 76
      level => 3
      group => "Axial"
      URL => "index.php?/tags/12-axial_rib"
    2 => Array (8)
      id => "13"
      name => "Sternum"
      url_name => "axial_sternum"
      lastmodified => "2020-02-18 10:42:13"
      counter => 76
      level => 3
      group => "Axial"
      URL => "index.php?/tags/13-axial_sternum"
    3 => Array (8)
      id => "11"
      name => "Vertebra"
      url_name => "axial_vertebra"
      lastmodified => "2020-02-18 10:42:13"
      counter => 76
      level => 3
      group => "Axial"
      URL => "index.php?/tags/11-axial_vertebra"
  TITLE => "Axial"
1 => Array (3)
  tags => Array (2)
    0 => Array (8)
      id => "17"
      name => "Pan"
      url_name => "extant_primates_pan"
      lastmodified => "2020-02-18 10:42:13"
      counter => 76
      level => 3
      group => "Extant primates"
      URL => "index.php?/tags/17-extant_primates_pan"
    1 => Array (8)
      id => "18"
      name => "Pongo"
      url_name => "extant_primates_pongo"
      lastmodified => "2020-02-18 10:42:13"
      counter => 76
      level => 3
      group => "Extant primates"
      URL => "index.php?/tags/18-extant_primates_pongo"
  CHANGE_COLUMN => true
  TITLE => "Extant primates"
</code>```

Array (2) is $tag_groups and the next two lower levels (i.e. 0 => Array (2) and 1 => Array (3)) are $tag_group.

How do I print only the TITLE of each $tag_group, or at least a sublevel?

I tried

```<code>{$tag_groups.TITLE|@debug_print_var}
{$tag_groups['tag_group']|@debug_print_var}
</code>```

And a few other variations and I either always get null or a php error (e.g. when I try {$tag_groups item='tag_group'|@debug_print_var}).

My thinking is that if I am able to print only the TITLE of each sublevel of the array I will then know what syntax to use in order to loop through it with an if condition, as what I want to do will look something like that

```<code>{foreach foreach from=$tag_groups item=tag_group.TITLE}
  {if in_array('Axial', $tag_group.TITLE)}
   DoSomethingAboutIt
  {/if}
{/foreach}
</code>```

But I am not even sure this is valid thinking.

Thanks for the help!

答:
Ok, I think I worked it out

```<code>{foreach from=$tag_groups item=tag_group}
    {$tag_group.TITLE|@debug_print_var}
{/foreach}
</code>```

I am coming from R so it just didn't make sense for me to loop through the array in order to print its subelements....

Body:
I am very new to Smarty and PHP in general and am quite struggling with multidimensional arrays. I have a multidimensional array called $tag_groups. When I print the array with {$tag_groups|@debug_print_var} I get the following output:

Array (2)
0 => Array (2)
  tags => Array (4)
    0 => Array (8)
      id => "10"
      name => "Os coxa"
      url_name => "axial_os_coxa"
      lastmodified => "2020-02-18 10:42:13"
      counter => 76
      level => 3
      group => "Axial"
      URL => "index.php?/tags/10-axial_os_coxa"
    1 => Array (8)
      id => "12"
      name => "Rib"
      url_name => "axial_rib"
      lastmodified => "2020-02-18 10:42:13"
      counter => 76
      level => 3
      group => "Axial"
      URL => "index.php?/tags/12-axial_rib"
    2 => Array (8)
      id => "13"
      name => "Sternum"
      url_name => "axial_sternum"
      lastmodified => "2020-02-18 10:42:13"
      counter => 76
      level => 3
      group => "Axial"
      URL => "index.php?/tags/13-axial_sternum"
    3 => Array (8)
      id => "11"
      name => "Vertebra"
      url_name => "axial_vertebra"
      lastmodified => "2020-02-18 10:42:13"
      counter => 76
      level => 3
      group => "Axial"
      URL => "index.php?/tags/11-axial_vertebra"
  TITLE => "Axial"
1 => Array (3)
  tags => Array (2)
    0 => Array (8)
      id => "17"
      name => "Pan"
      url_name => "extant_primates_pan"
      lastmodified => "2020-02-18 10:42:13"
      counter => 76
      level => 3
      group => "Extant primates"
      URL => "index.php?/tags/17-extant_primates_pan"
    1 => Array (8)
      id => "18"
      name => "Pongo"
      url_name => "extant_primates_pongo"
      lastmodified => "2020-02-18 10:42:13"
      counter => 76
      level => 3
      group => "Extant primates"
      URL => "index.php?/tags/18-extant_primates_pongo"
  CHANGE_COLUMN => true
  TITLE => "Extant primates"

Array (2) is $tag_groups and the next two lower levels (i.e. 0 => Array (2) and 1 => Array (3)) are $tag_group.

How do I print only the TITLE of each $tag_group, or at least a sublevel?

I tried

{$tag_groups.TITLE|@debug_print_var}
{$tag_groups['tag_group']|@debug_print_var}

And a few other variations and I either always get null or a php error (e.g. when I try {$tag_groups item='tag_group'|@debug_print_var}).

My thinking is that if I am able to print only the TITLE of each sublevel of the array I will then know what syntax to use in order to loop through it with an if condition, as what I want to do will look something like that

{foreach foreach from=$tag_groups item=tag_group.TITLE}
  {if in_array('Axial', $tag_group.TITLE)}
   DoSomethingAboutIt
  {/if}
{/foreach}

But I am not even sure this is valid thinking.

Thanks for the help!

Body:
Ok, I think I worked it out

{foreach from=$tag_groups item=tag_group}
    {$tag_group.TITLE|@debug_print_var}
{/foreach}

I am coming from R so it just didn't make sense for me to loop through the array in order to print its subelements....


问:
How to individually select every single matching selector
I'm trying to create a script with jQuery where it finds elements with the class "timeAgo" and replace its innerHTML with how long ago the time in the create attribute was. Here's what I have:

```<code>function timeAgo(time) {
  var d = new Date();
  var diff = Math.floor((d.getTime() - time)/1000);
  if (diff >= 31536000) {
    if (Math.floor(diff/31536000) == 1) {
      return (Math.floor(diff/31536000) + " year ago");
    } else {
      return (Math.floor(diff/31536000) + " years ago");
    }
  } else if (diff >= 2592000) {
    if (Math.floor(diff/2592000) == 1) {
      return (Math.floor(diff/2592000) + " month ago");
    } else {
      return (Math.floor(diff/2592000) + " months ago");
    }
  } else if (diff >= 86400) {
    if (Math.floor(diff/86400) == 1) {
      return (Math.floor(diff/86400) + " day ago");
    } else {
      return (Math.floor(diff/86400) + " days ago");
    }
  } else if (diff >= 3600) {
    if (Math.floor(diff/3600) == 1) {
      return (Math.floor(diff/3600) + " hour ago");
    } else {
      return (Math.floor(diff/3600) + " hours ago");
    }
  } else if (diff >= 60) {
    if (Math.floor(diff/60) == 1) {
      return (Math.floor(diff/60) + " minute ago");
    } else {
      return (Math.floor(diff/60) + " minutes ago");
    }
  } else {
    if (diff == 1) {
      return (diff + " second ago");
    } else {
      return (diff + " seconds ago");
    }
  }
}
$(document).ready(function () {
  $(".timeAgo").innerHTML(timeAgo($(".timeAgo").attr("create")));
}
</code>```

But whenever I run the code with multiple instances of ".timeAgo", it sets all of them to the first instance of ".timeAgo". How do I make it so that it uses each separate instance?

答:
Use each to loop through them, and $(this) within each to access each individual one:

```<code>$(".timeAgo").each(function() {
    var $el = $(el);
    $el.html(timeAgo($el.attr("create")));
});
</code>```

Also note using html(), not innerHTML =. Although within the callback, there's really no need for jQuery:

```<code>$(".timeAgo").each(function() {
    this.innerHTML = timeAgo(this.getAttribute("create"));
});
</code>```

In fact, you don't need jQuery at all in any modern browser (but this won't work in IE11 unless you follow my steps here to polyfill forEach):

```<code>document.querySelector(".timeAgo").forEach(function(element) {
    element.innerHTML = timeAgo(element.getAttribute("create"));
});
</code>```

Side note: You appear to be creating elements with a non-standard create attribute. The WHAT-WG and W3C recommendation is not to do that, since it's always possible that attribute will be assigned standard meaning sometime in the future. Instead, use data-create (a data-* attribute) and access it via .attr("data-create"). (See my answer here for why you may or may not want to use .data("create") instead to access it.)

```<code>$(".timeAgo").each(function() {
    var $el = $(this);
    $el.html(timeAgo($el.attr("data-create")));
});
</code>```

or

```<code>$(".timeAgo").each(function() {
    this.innerHTML = timeAgo(this.getAttribute("data-create"));
});
</code>```

or (with polyfill for IE11 if needed)

```<code>document.querySelector(".timeAgo").forEach(function(element) {
    element.innerHTML = timeAgo(element.getAttribute("data-create"));
});
</code>```

Body:
I'm trying to create a script with jQuery where it finds elements with the class "timeAgo" and replace its innerHTML with how long ago the time in the create attribute was. Here's what I have:

function timeAgo(time) {
  var d = new Date();
  var diff = Math.floor((d.getTime() - time)/1000);
  if (diff >= 31536000) {
    if (Math.floor(diff/31536000) == 1) {
      return (Math.floor(diff/31536000) + " year ago");
    } else {
      return (Math.floor(diff/31536000) + " years ago");
    }
  } else if (diff >= 2592000) {
    if (Math.floor(diff/2592000) == 1) {
      return (Math.floor(diff/2592000) + " month ago");
    } else {
      return (Math.floor(diff/2592000) + " months ago");
    }
  } else if (diff >= 86400) {
    if (Math.floor(diff/86400) == 1) {
      return (Math.floor(diff/86400) + " day ago");
    } else {
      return (Math.floor(diff/86400) + " days ago");
    }
  } else if (diff >= 3600) {
    if (Math.floor(diff/3600) == 1) {
      return (Math.floor(diff/3600) + " hour ago");
    } else {
      return (Math.floor(diff/3600) + " hours ago");
    }
  } else if (diff >= 60) {
    if (Math.floor(diff/60) == 1) {
      return (Math.floor(diff/60) + " minute ago");
    } else {
      return (Math.floor(diff/60) + " minutes ago");
    }
  } else {
    if (diff == 1) {
      return (diff + " second ago");
    } else {
      return (diff + " seconds ago");
    }
  }
}
$(document).ready(function () {
  $(".timeAgo").innerHTML(timeAgo($(".timeAgo").attr("create")));
}

But whenever I run the code with multiple instances of ".timeAgo", it sets all of them to the first instance of ".timeAgo". How do I make it so that it uses each separate instance?

Body:
Use each to loop through them, and $(this) within each to access each individual one:

$(".timeAgo").each(function() {
    var $el = $(el);
    $el.html(timeAgo($el.attr("create")));
});

Also note using html(), not innerHTML =. Although within the callback, there's really no need for jQuery:

$(".timeAgo").each(function() {
    this.innerHTML = timeAgo(this.getAttribute("create"));
});

In fact, you don't need jQuery at all in any modern browser (but this won't work in IE11 unless you follow my steps here to polyfill forEach):

document.querySelector(".timeAgo").forEach(function(element) {
    element.innerHTML = timeAgo(element.getAttribute("create"));
});

Side note: You appear to be creating elements with a non-standard create attribute. The WHAT-WG and W3C recommendation is not to do that, since it's always possible that attribute will be assigned standard meaning sometime in the future. Instead, use data-create (a data-* attribute) and access it via .attr("data-create"). (See my answer here for why you may or may not want to use .data("create") instead to access it.)

$(".timeAgo").each(function() {
    var $el = $(this);
    $el.html(timeAgo($el.attr("data-create")));
});

or

$(".timeAgo").each(function() {
    this.innerHTML = timeAgo(this.getAttribute("data-create"));
});

or (with polyfill for IE11 if needed)

document.querySelector(".timeAgo").forEach(function(element) {
    element.innerHTML = timeAgo(element.getAttribute("data-create"));
});


问:
React-admin table displays twice
From some reason the code I write here build 2 tables and displaying both.
I tried to re-write it many times and still displaying 2 tables.

users.js

results:

what should I try?

答:
The <Admin> component should only have <Resource> components as children. Your <Users> component should be passed as the list prop of a resource:

```<code>const App = () =>
   <Admin dataProvider={myDataProvider}>
       <Resource list={Users} />
   </Admin>;
</code>```

This is well documented in https://marmelab.com/react-admin/Tutorial.html#mapping-api-endpoints-with-resources

Title: React-admin table displays twice

Body:
The <Admin> component should only have <Resource> components as children. Your <Users> component should be passed as the list prop of a resource:

const App = () =>
   <Admin dataProvider={myDataProvider}>
       <Resource list={Users} />
   </Admin>;

This is well documented in https://marmelab.com/react-admin/Tutorial.html#mapping-api-endpoints-with-resources


问:
Calling a function defined in a TypeScript file from an HTML input onchange attribute
If I had a JavaScript index.js file like this:

```<code>function foo(val) {
  console.log(val);
}
</code>```

and a index.html HTML file like this:

```<code>...
<script src="./index.js"></script>
<div id="container">
  <label>bar
    <input type="radio" name="radio" value="bar" onchange="foo(value);"/>
  </label>
  <label>baz
    <input type="radio" name="radio" value="baz" onchange="foo(value);"/>
  </label>
...
</code>```

this would log bar or baz as I check a radio button.

I want to call foo(value) which is defined in a index.ts TypeScript file like this:

```<code>let foo = (value: string): void => {
  console.log(value);
};
</code>```

In index.html I change  to , then I use parcel to build the app, but the resulting built file is not able to call the function, logging  referenceError: setLayer is not defined.

I know that in theory the browser does not know anything about TypeScript and only knows JavaScript, but after compiling with parcel in my dist dir I see a bunch of *js files, one of which I thought might have included the compiled foo() function.

So the question is: how can I call a function inside a TS file from a HTML input onchange attribute like I would do with a JS file?

Last but not least: to build my app I invoke parcel start (or even parcel run build), and my package.json looks like this:

```<code>{
  "name": "app_test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start:build": "tsc -w",
    "start": "parcel index.html",
    "build": "parcel build --public-url . index.html"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
  },
  "devDependencies": {
    "parcel-bundler": "^1.12.4",
    "typescript": "^3.7.5"
  }
}
</code>```

答:
Instead of referencing to index.ts directly from your index.html file, try pointing to the compiled files in /dist like so:

```<code><script src="dist/index.js"></script>
</code>```

As you correctly stated, TypeScript is simply a superset of JavaScript and can't not be interpreted by your browser - only after compiling it to JavaScript.

Body:
If I had a JavaScript index.js file like this:

function foo(val) {
  console.log(val);
}

and a index.html HTML file like this:

...

  bar
    <input type="radio" name="radio" value="bar" onchange="foo(value);"/>

  baz
    <input type="radio" name="radio" value="baz" onchange="foo(value);"/>

...

this would log bar or baz as I check a radio button.

I want to call foo(value) which is defined in a index.ts TypeScript file like this:

let foo = (value: string): void => {
  console.log(value);
};

In index.html I change  to , then I use parcel to build the app, but the resulting built file is not able to call the function, logging  referenceError: setLayer is not defined.

I know that in theory the browser does not know anything about TypeScript and only knows JavaScript, but after compiling with parcel in my dist dir I see a bunch of *js files, one of which I thought might have included the compiled foo() function.

So the question is: how can I call a function inside a TS file from a HTML input onchange attribute like I would do with a JS file?

Last but not least: to build my app I invoke parcel start (or even parcel run build), and my package.json looks like this:

{
  "name": "app_test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start:build": "tsc -w",
    "start": "parcel index.html",
    "build": "parcel build --public-url . index.html"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
  },
  "devDependencies": {
    "parcel-bundler": "^1.12.4",
    "typescript": "^3.7.5"
  }
}

Body:
Instead of referencing to index.ts directly from your index.html file, try pointing to the compiled files in /dist like so:

<script src="dist/index.js"></script>

As you correctly stated, TypeScript is simply a superset of JavaScript and can't not be interpreted by your browser - only after compiling it to JavaScript.


问:
How to update database table schemas with NHibernate schema generation?
I'm trying to figure out how to use NHibernate configuration with mapping to update table schemas, rather than dropping and recreating them.

Currently I'm using the NHibernate.Tool.hbm2ddl.SchemaExport obj with FluentNHibernate to generate the database schema for a mysql database.  While I can't say it's a huge problem, whenever I call SchemaExport.Execute on the database, it's going to drop all the tables and then recreate them.

What would be way cooler is if I could just have it update the existing table structures retaining data where possible.  But I don't really want to use a commerical product, or a code generator, because I don't like code generation in general, and I don't need this enough that I would consider paying for it. So hopefully any answer would keep these caveats in mind.

答:
The SchemaUpdate object provides database schema updating, by apparently generating and executing a series of SQL UPDATE statements (as well as constraint statements) when it's void Execute(bool script, bool doUpdate)
 function is called.  The SchemaUpdate class is in the NHibernate.Tool.hbm2ddl namespace, which can be found in the Nhibernate.dll file.

SchemaUpdate is mentioned in chapter 15 of the nhibernate 1.0.2 toolset guide, here (section 15.1.5).

"The NHibernate FAQ" had (link now expired) a more complete example of how to use SchemaUpdate:

```<code>[Test]
public void Update_an_existing_database_schema()
{
    _cfg = new Configuration();
    _cfg.Configure();
    _cfg.AddAssembly(Assembly.LoadFrom("DataLayer.dll"));
    var update = new SchemaUpdate(_cfg);
    update.Execute(true, false);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
The SchemaUpdate object provides database schema updating, by apparently generating and executing a series of SQL UPDATE statements (as well as constraint statements) when it's void Execute(bool script, bool doUpdate)
 function is called.  The SchemaUpdate class is in the NHibernate.Tool.hbm2ddl namespace, which can be found in the Nhibernate.dll file.

SchemaUpdate is mentioned in chapter 15 of the nhibernate 1.0.2 toolset guide, here (section 15.1.5).

"The NHibernate FAQ" had (link now expired) a more complete example of how to use SchemaUpdate:

[Test]
public void Update_an_existing_database_schema()
{
    _cfg = new Configuration();
    _cfg.Configure();
    _cfg.AddAssembly(Assembly.LoadFrom("DataLayer.dll"));
    var update = new SchemaUpdate(_cfg);
    update.Execute(true, false);
}


问:
windows service exception in .NET
I will be tested the application as windows application then it will be stored the datetime in MySQL data base.When I will be start this application using windows service it will be thrown this exception.

 ```
error [HY000][MySQL][ODBC 3.51 Driver] [MySqlid -6.0.11-alpha-community]incorrect datetime value " 5/6/2011 9:00:00 AM" for column column-name at row1
 ```

Windows application take the system format & my system format is yyyy-MM-dd hh:mm:ss
in windows service which format is used.

```
query18 += "select '" + obj8 + "' as DTvalue ,'" + date8 + "' as DTdatelogged1 ,'" + OpcGroup.QualityToString(e8.sts[counter8].Quality) + "' as DTquality ,'" + DateTime.FromFileTime(e8.sts[counter8].TimeStamp) + "' as DTtimestamp ,'" + e8.sts[counter8].HandleClient + "' as DTparamID Union " + Environment.NewLine;

UpdateQuery = Update parameter t Left join + Environment.NewLine;
                    UpdateQuery8 +=  (  + query18 +  ) Temp on" + Environment.NewLine;
                    UpdateQuery8 += t.itemID=Temp.DTparamID+ Environment.NewLine;
                    UpdateQuery8 += set paramvalue=DTvalue, date_logged1=DTdatelogged1,Quality=                         DTquality,date_logged=DTtimestamp   + Environment.NewLine;
                    UpdateQuery8 += where t.groupID=9 and t.itemID=Temp.DTparamID;

```

my query likethis timestamp value is 129500892576718750 it will be convert DateTime.FromFileTime() function converted value like '2011-05-17 12:30:57' in windows application it will be write into mysql database
but in windows service converted value like 2011/05/17 12:30:57 PM it will be not accepted by the MYSQL database same thing i will be used in the windows service

now

```
UpdateQuery8 = "Update parameter " + Environment.NewLine;
                        UpdateQuery8 += "set paramvalue=@paramvalue,date_logged1=@date_logged1,Quality=@Quality,date_logged=@date_logged" + Environment.NewLine;
UpdateQuery8 += "where groupID=9 and itemID=@itemID";
                        cmd8 = new OdbcCommand(UpdateQuery8, con136);
  cmd8.Parameters.Add("@paramvalue",  obj8.ToString());
  cmd8.Parameters.Add("@date_logged1", date8);
 cmd8.Parameters.Add("@Quality", OpcGroup.QualityToString(e8.sts[counter8].Quality));
  cmd8.Parameters.Add("@date_logged", dt);
  cmd8.Parameters.Add("@itemID",e8.sts[counter8].HandleClient);
  cmd8.ExecuteNonQuery();
```

it will be execute but there no updation in database

Please help me in this regard.

Thanks in Advance.

答:
Create a datetime and format it the way YOU want. Not the system defaults, not the casual user defaults, the one you want.

```<code>DateTime dt = DateTime.Now;
String str = dt.ToString("yyyyMMdd");
</code>```

This should lead to "20110517" if i'm not mistaking.

Bonus points are given if you use one of the better answers setting the code locale to the one used by the mysql server. But the one above should give you a way that works.

Title: windows service exception in .NET

Body:
I will be tested the application as windows application then it will be stored the datetime in MySQL data base.When I will be start this application using windows service it will be thrown this exception.

error [HY000][MySQL][ODBC 3.51 Driver] [MySqlid -6.0.11-alpha-community]incorrect datetime value " 5/6/2011 9:00:00 AM" for column column-name at row1

Windows application take the system format & my system format is yyyy-MM-dd hh:mm:ss
in windows service which format is used.

query18 += "select '" + obj8 + "' as DTvalue ,'" + date8 + "' as DTdatelogged1 ,'" + OpcGroup.QualityToString(e8.sts[counter8].Quality) + "' as DTquality ,'" + DateTime.FromFileTime(e8.sts[counter8].TimeStamp) + "' as DTtimestamp ,'" + e8.sts[counter8].HandleClient + "' as DTparamID Union " + Environment.NewLine;

UpdateQuery = Update parameter t Left join + Environment.NewLine;
                    UpdateQuery8 +=  (  + query18 +  ) Temp on" + Environment.NewLine;
                    UpdateQuery8 += t.itemID=Temp.DTparamID+ Environment.NewLine;
                    UpdateQuery8 += set paramvalue=DTvalue, date_logged1=DTdatelogged1,Quality=                         DTquality,date_logged=DTtimestamp   + Environment.NewLine;
                    UpdateQuery8 += where t.groupID=9 and t.itemID=Temp.DTparamID;

my query likethis timestamp value is 129500892576718750 it will be convert DateTime.FromFileTime() function converted value like '2011-05-17 12:30:57' in windows application it will be write into mysql database
but in windows service converted value like 2011/05/17 12:30:57 PM it will be not accepted by the MYSQL database same thing i will be used in the windows service

now

UpdateQuery8 = "Update parameter " + Environment.NewLine;
                        UpdateQuery8 += "set paramvalue=@paramvalue,date_logged1=@date_logged1,Quality=@Quality,date_logged=@date_logged" + Environment.NewLine;
UpdateQuery8 += "where groupID=9 and itemID=@itemID";
                        cmd8 = new OdbcCommand(UpdateQuery8, con136);
  cmd8.Parameters.Add("@paramvalue",  obj8.ToString());
  cmd8.Parameters.Add("@date_logged1", date8);
 cmd8.Parameters.Add("@Quality", OpcGroup.QualityToString(e8.sts[counter8].Quality));
  cmd8.Parameters.Add("@date_logged", dt);
  cmd8.Parameters.Add("@itemID",e8.sts[counter8].HandleClient);
  cmd8.ExecuteNonQuery();

it will be execute but there no updation in database

Please help me in this regard.

Thanks in Advance.

Body:
Create a datetime and format it the way YOU want. Not the system defaults, not the casual user defaults, the one you want.

DateTime dt = DateTime.Now;
String str = dt.ToString("yyyyMMdd");

This should lead to "20110517" if i'm not mistaking.

Bonus points are given if you use one of the better answers setting the code locale to the one used by the mysql server. But the one above should give you a way that works.


问:
nodejs - Is it possible to run a node script located in a folder mentioned in path environment variable without giving absolute path to that file?
There is a folder C:/commandline_shortcuts in my PC which I already added to environment variable Path. I use this folder to put tiny batch scripts that I can run from any directory which works perfectly fine. Today I created a node script, which I want to put in this folder for the same purpose. It only works when I run

D:/someOtherFolder> node C:/commandline_shortcuts/my-script cmdLineArg1 cmdLineArg2

but I want to run it like

D:/someOtherFolder> node my-script cmdLineArg1 cmdLineArg2

Is this possible ?

答:
It does not work because node is the actual command, not my-script.

You can create a my-script.sh in the shortcut folder which runs

```<code>C:/commandline_shortcuts/my-script $1 $1
</code>```

Body:
It does not work because node is the actual command, not my-script.

You can create a my-script.sh in the shortcut folder which runs

C:/commandline_shortcuts/my-script $1 $1


问:
"Parse Error : There is a problem parsing the package" while installing Android application
I got this error while installing the android application (Parse Error : There is a problem parsing the package.). I did the following steps.

First time I installed the application and it works fine.

I made changes to the existing application and change the version no in Manifest file.

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.openintents.samples.BasicOpenARDemo" android:versionCode="2" android:versionName="1.0.1">
</code>```

Then I export the application and finish the code signing process.
For this, Right Click your Project node > select Export. There you will see a wizard. Follow the steps and finish the code signing also.

I got the ARDemo.apk file, Then I changed it’s name to ARDemo1.apk

Then I shipped this apk file to mobiles SD Card and started the installation I got the above error.

I googled, they say that problem with unpacking manifest file.

Can anyone tell me what could be wrong with me?

答:
In my case I signed with only V2 signature (from Android 7 onward) but tried to install on 5 and 6. Adding V1 during ARK generation/signing fixed the issue.

See Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?.

Body:
I got this error while installing the android application (Parse Error : There is a problem parsing the package.). I did the following steps.

First time I installed the application and it works fine.

I made changes to the existing application and change the version no in Manifest file.

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.openintents.samples.BasicOpenARDemo" android:versionCode="2" android:versionName="1.0.1">

Then I export the application and finish the code signing process.
For this, Right Click your Project node > select Export. There you will see a wizard. Follow the steps and finish the code signing also.

I got the ARDemo.apk file, Then I changed it’s name to ARDemo1.apk

Then I shipped this apk file to mobiles SD Card and started the installation I got the above error.

I googled, they say that problem with unpacking manifest file.

Can anyone tell me what could be wrong with me?


问:
TransformXml task could not be loaded from Microsoft.Web.Publishing.Tasks.dll
Has anyone seen this error and know how to fix it?

The "TransformXml" task could not be loaded from the assembly C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\Web\Microsoft.Web.Publishing.Tasks.dll.

Could not load file or assembly 'file:///C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\Web\Microsoft.Web.Publishing.Tasks.dll' or one of its dependencies. The system cannot find the file specified.

Confirm that the  declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.

I read elsewhere that the problem is when you don't have SQL Server installed. But I do have SQL Express 2012 x64 installed with SP1. I am also running VS 2013 Professional.

I have ran this exact same solution in VS 2012 express with no problems.

答:
For me it started working just by adding reference to the NuGet package MSBuild.Microsoft.VisualStudio.Web.targets v14.0.0.3

Even no need to add UsingTask element to the project file as it mentioned by the package author

https://github.com/pdonald/nuget-webtargets

Just install the NuGet package. The package automatically sets the
$(VSToolsPath) property to use the targets file in the tools folder.

And then I was able to use TransformXml and other tasks, defined in the package, for instance to transform app.config

```<code>  <Target Name="app_config_AfterCompile" AfterTargets="AfterCompile" Condition="Exists('app.$(Configuration).config')">
    <!--Generate transformed app config in the intermediate directory-->
    <TransformXml Source="app.config" Destination="$(IntermediateOutputPath)$(TargetFileName).config" Transform="app.$(Configuration).config" />
    <!--Force build process to use the transformed configuration file from now on.-->
    <ItemGroup>
      <AppConfigWithTargetPath Remove="App.config" />
      <AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">
        <TargetPath>$(TargetFileName).config</TargetPath>
      </AppConfigWithTargetPath>
    </ItemGroup>
  </Target>
</code>```

Body:
For me it started working just by adding reference to the NuGet package MSBuild.Microsoft.VisualStudio.Web.targets v14.0.0.3

Even no need to add UsingTask element to the project file as it mentioned by the package author

https://github.com/pdonald/nuget-webtargets

Just install the NuGet package. The package automatically sets the
$(VSToolsPath) property to use the targets file in the tools folder.

And then I was able to use TransformXml and other tasks, defined in the package, for instance to transform app.config

  <Target Name="app_config_AfterCompile" AfterTargets="AfterCompile" Condition="Exists('app.$(Configuration).config')">
    <!--Generate transformed app config in the intermediate directory-->
    <TransformXml Source="app.config" Destination="$(IntermediateOutputPath)$(TargetFileName).config" Transform="app.$(Configuration).config" />
    <!--Force build process to use the transformed configuration file from now on.-->
    <ItemGroup>
      <AppConfigWithTargetPath Remove="App.config" />
      <AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">
        <TargetPath>$(TargetFileName).config</TargetPath>
      </AppConfigWithTargetPath>
    </ItemGroup>
  </Target>


问:
SSH.NET SocketException An attempt was made to access a socket in a way forbidden by its access permissions
I'm using SSH.NET to access some folders to show  on my website via SFTP host and port 22.

but it gives me an exception after uploading the function's page to the online host "smarterasp.net"..

```<code>[SocketException (0x271d): An attempt was made to access a socket in a way forbidden by its access permissions]
</code>```

How can I solve this problem ?

答: If this is a Visual Studio project with a package manifest you may be able to resolve this issue by modifying the capabilities of the package manifest to include "Private Networks (Client & Server)". You can find the package manifest in your project properties.</p>

Body:
I'm using SSH.NET to access some folders to show  on my website via SFTP host and port 22.

but it gives me an exception after uploading the function's page to the online host "smarterasp.net"..

[SocketException (0x271d): An attempt was made to access a socket in a way forbidden by its access permissions]

How can I solve this problem ?


问:
Is it possible to start a docker container with some env variables from the docker API
I'm using docker API to manage my containers from a front-end application and I would like to know if it was possible to use /container/{id}/start with some environnement variables, i can't find it in the official doc.

Thanks !

答: You can only specify environment variables when creating a container.  Starting it just starts the main process in the container that already exists with its existing settings; the “start” API call has almost no options beyond the container ID.  If you’ve stopped a container and want to restart it with different options, you need to delete and recreate it.</p>


问:
responsive dc.js chart is taking over the whole window
I'm having trouble making my chart responsive, I'm trying to apply the same example with DC.js and Crossfilter that is at this link: resizing-series.

The chart is responsive, however, there are some bugs when interacting with the tables I have. For example, when I click on either the graph or any of the tables, the graph becomes very large, occupying the entire screen. As shown in the image below:

When I leave the screen split with Console, the graph is rendered responsively, as I change the screen size the size of the graph is also changed, however, if I leaveConsole the graph remains occupying the entire the screen and does not return to the default initial size shown in the first image.

Does anyone know how to tell me how to fix these bugs? I couldn't understand why this is happening.

Thnaks in advance.

var composite = dc.compositeChart('#composite');
var vendedorTable = dc.dataTable("#vendedores");
var citiesTable = dc.dataTable("#cities");

function remove_empty_bins(source_group) {
  return {
    top: function(N) {
      return source_group.all().filter(function(d) {
        return d.value.totalAno > 1e-3 ||
          d.value.totalHomologo > 1e-3;
      }).slice(0, N);
    }
  };
}

var url = 'https://gist.githubusercontent.com/bernalvinicius/3cece295bc37de1697e7f83418e7fcc9/raw/a5820379ec6eae76ee792495cc5dd1685c977a73/vendedores.json';
d3.json(url).then(function(data) {

  data.forEach(d =>
    Object.assign(d, {
      mes: d.Month,
      atual: d.Vendas_Ano,
      passado: d.Vendas_Ant
    })
  );
  var cf = crossfilter(data);

  vendedorDim = cf.dimension(function(d) {
    return d.vendnm;
  });
  var vendedorGroup = vendedorDim.group().reduce(reduceAdd, reduceRemove, reduceInitial);

  citiesDim = cf.dimension(function(d) {
    return d.zona;
  });
  var citiesGroup = citiesDim.group().reduce(reduceAdd, reduceRemove, reduceInitial);

  var dim = cf.dimension(dc.pluck('mes')),
    grp1 = dim.group().reduceSum(dc.pluck('atual')),
    grp2 = dim.group().reduceSum(dc.pluck('passado'));
  var minMonth = dim.bottom(1)[0].mes;
  var maxMonth = dim.top(1)[0].mes;

  var all = cf.groupAll();

  dc.dataCount(".dc-data-count")
    .dimension(cf)
    .group(all);

  function reduceAdd(p, v) {
    p.totalAno += +v.Vendas_Ano;
    p.totalHomologo += +v.Vendas_Ant;
    return p;
  }

  function reduceRemove(p, v) {
    p.totalAno -= v.Vendas_Ano;
    p.totalHomologo -= v.Vendas_Ant;
    return p;
  }

  function reduceInitial() {
    return {
      totalAno: 0,
      totalHomologo: 0,
    };
  }

  // Fake Dimension
  rank = function(p) {
    return ""
  };

  // Chart by months
  composite
    .width(600)
    .height(300)
    .x(d3.scaleLinear().domain([1, 12]))
    .yAxisLabel("")
    .xAxisLabel("Month")
    .legend(dc.legend().x(500).y(0).itemHeight(13).gap(5))
    .renderHorizontalGridLines(true)
    .compose([
      dc.lineChart(composite)
      .dimension(dim)
      .colors('steelblue')
      .group(grp1, "Currently Year"),
      dc.lineChart(composite)
      .dimension(dim)
      .colors('darkorange')
      .group(grp2, "Last Year")
    ])
    .brushOn(true);

  composite.brush().extent([-0.5, data.length + 1.5])
  composite.extendBrush = function(brushSelection) {
    if (brushSelection) {
      vendedorTable.filter(null);
      vendedorDim.filter(null);
      citiesTable.filter(null);
      citiesDim.filter(null);
      const point = Math.round((brushSelection[0] + brushSelection[1]) / 2);
      return [
        point - 0.5,
        point + 0.5
      ];
    }
  };

  // Sales Table
  vendedorTable.width(500)
    .height(480)
    .dimension(remove_empty_bins(vendedorGroup))
    .group(rank)
    .columns([function(d) {
        return d.key;
      },
      function(d) {
        return Number(Math.round(d.value.totalAno * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      },
      function(d) {
        return Number(Math.round(d.value.totalHomologo * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      }
    ])
    .sortBy(function(d) {
      return d.value.totalAno
    })
    .order(d3.descending)

  // Cities Table
  citiesTable.width(500)
    .height(480)
    .dimension(remove_empty_bins(citiesGroup))
    .group(rank)
    .columns([function(d) {
        return d.key;
      },
      function(d) {
        return Number(Math.round(d.value.totalAno * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      },
      function(d) {
        return Number(Math.round(d.value.totalHomologo * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      }
    ])
    .sortBy(function(d) {
      return d.value.totalAno
    })
    .order(d3.descending)

  // Sales click events
  vendedorTable.on('pretransition', function(table) {
    table.selectAll('td.dc-table-column')
      .on('click', function(d) {
        let filters = table.filters().slice();
        if (filters.indexOf(d.key) === -1)
          filters.push(d.key);
        else
          filters = filters.filter(k => k != d.key);
        if (filters.length === 0)
          vendedorDim.filter(null);
        else
          vendedorDim.filterFunction(function(d) {
            return filters.indexOf(d) !== -1;
          })
        table.replaceFilter([filters]);

        citiesTable.filter(null);
        citiesDim.filter(null);
        composite.filter(null);

        dc.redrawAll();
      });
    let filters = table.filters();
    table.selectAll('tr.dc-table-row')
      .classed('sel-rows', d => filters.indexOf(d.key) !== -1);
  });

  // Cities click events
  citiesTable.on('pretransition', function(table) {
    table.selectAll('td.dc-table-column')
      .on('click', function(d) {
        let filters = table.filters().slice();
        if (filters.indexOf(d.key) === -1)
          filters.push(d.key);
        else
          filters = filters.filter(k => k != d.key);
        if (filters.length === 0)
          citiesDim.filter(null);
        else
          citiesDim.filterFunction(function(d) {
            return filters.indexOf(d) !== -1;
          })
        table.replaceFilter([filters]);

        vendedorTable.filter(null);
        vendedorDim.filter(null);
        composite.filter(null);

        dc.redrawAll();
      });
    let filters = table.filters();
    table.selectAll('tr.dc-table-row')
      .classed('sel-rows', d => filters.indexOf(d.key) !== -1);
  });

  dc.renderAll();

  // reset functions
  $('#reset').on('click', function() {
    vendedorTable.filter(null);
    vendedorDim.filter(null);
    citiesTable.filter(null);
    citiesDim.filter(null);
    composite.filter(null);

    dc.redrawAll();
  });

  $('#resetTable').on('click', function() {
    vendedorTable.filter(null);
    vendedorDim.filter(null);
    citiesTable.filter(null);
    citiesDim.filter(null);
    composite.filter(null);

    dc.redrawAll();
  });

  $('#resetTable2').on('click', function() {
    vendedorTable.filter(null);
    vendedorDim.filter(null);
    citiesTable.filter(null);
    citiesDim.filter(null);
    composite.filter(null);

    dc.redrawAll();
  });

  /****************************************************************************/
  // Functions to handle responsive

  var adjustX = 10,
    adjustY = 40;

  apply_resizing(composite, adjustX, adjustY, function(composite) {
    composite.legend().x(window.innerWidth - 200);
  });

  var find_query = function() {
    var _map = window.location.search.substr(1).split('&').map(function(a) {
      return a.split('=');
    }).reduce(function(p, v) {
      if (v.length > 1)
        p[v[0]] = decodeURIComponent(v[1].replace(/\+/g, " "));
      else
        p[v[0]] = true;
      return p;
    }, {});
    return function(field) {
      return _map[field] || null;
    };
  }();

  var resizeMode = find_query('resize') || 'widhei';

  function apply_resizing(composite, adjustX, adjustY, onresize) {
    if (resizeMode === 'viewbox') {
      composite
        .width(300)
        .height(200)
        .useViewBoxResizing(true);
      d3.select(composite.anchor()).classed('fullsize', false);
    } else {
      adjustX = adjustX || 0;
      adjustY = adjustY || adjustX || 0;
      composite
        .width(window.innerWidth - adjustX)
        .height(window.innerHeight - adjustY);
      window.onresize = function() {
        if (onresize) {
          onresize(composite);
        }
        composite
          .width(window.innerWidth - adjustX)
          .height(window.innerHeight - adjustY);

        if (composite.rescale) {
          composite.rescale();
        }
        composite.redraw();
      };
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#composite {
  padding: 10px;
}

.dc-table-group {
  visibility: collapse;
}

tr.dc-table-row.sel-rows {
  background-color: lightblue;
}

.brush .custom-brush-handle {
  display: none;
}</code>```

<link rel="shortcut icon" href="https://img.icons8.com/nolan/64/puzzle.png">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dc/2.1.8/dc.css">

<title>12</title>

            Fictitious company data | Drilldown Example |

                             selected from
             records |
             Reset

                Sales
                Current Year
                Last Year

                City
                Current Year
                Last Year

```

答:
Thanks for posting an example! The bug doesn't show up in the SO code snippet feature unless you go to full page mode. I found your fiddle easier to work with.

Note: this is a complete rewrite of my previous answer, which was not clear.

1. Using ResizeObserver

updated 4/28/20

As of Safari 13.1 (released March 24 2020) all modern browsers support ResizeObserver. This is the cleanest way to detect chart resizing.

I recommend

Use a top-down layout such as flexbox or grid to position the  divs for your charts

Use ResizeObserver to determine when the div has changed size

Tell the charts to detect the chart div size using .width(null).height(null)

There is currently one resizing example that does this.

The special value null tells the chart to make the SVG node the same size as its parent div:

```<code>chart1.width(null)
    .height(null)
</code>```

The callback uses a helper function to disable transitions, because transitions just slow resizing down and make it look clunky:

```<code>const callback = chart => entries => {
    redraw_chart_no_transitions(
        chart
            .width(null)
            .height(null)
            .rescale());
    };
</code>```

Setting up the observer looks like

```<code>new ResizeObserver(callback(chart1)).observe(d3.select('#test1').node());
</code>```

Please see the example for more details.

2. Using window.onresize

The other resizing examples watch for window.onresize because until recently that was the only efficient, reliable cross-browser way to detect changes.

They calculate chart sizes based on the window size, which works well if your layout is bottom-up, e.g. using the default float: left layout.

Here is the function which sets this up:

```<code>function apply_resizing(chart, adjustX, adjustY, onresize) {
    if(!Array.isArray(chart))
        chart = [chart];
    if(!isNaN(adjustX))
        adjustX = (dx => x => x-dx)(adjustX);
    adjustX = adjustX || (x => x);
    if(!isNaN(adjustY))
        adjustY = (dy => y => y-dy)(adjustY);
    adjustY = adjustY || adjustX || (y => y);
    chart.forEach(c => c.width(adjustX(window.innerWidth))
                  .height(adjustY(window.innerHeight)));
    window.onresize = function () {
        if (onresize) {
            chart.forEach(onresize);
        }
        chart.forEach(c => {
            c.width(adjustX(window.innerWidth))
                .height(adjustY(window.innerHeight));
            if (c.rescale) {
                c.rescale();
            }
        });
        redraw_chart_no_transitions(chart);
    };
}
</code>```

A single chart can be initialized like so:

```<code>apply_resizing(chart, 20);
</code>```

This fills the window but makes the chart 20 pixels less wide.

The function can also take multiple charts in an array, and adjustment functions to support complicated layouts, like one where two charts should split the window vertically:

```<code>apply_resizing([heatmapChart, barChart], 20, y => y/2-fudge);
</code>```

Body:
I'm having trouble making my chart responsive, I'm trying to apply the same example with DC.js and Crossfilter that is at this link: resizing-series.

The chart is responsive, however, there are some bugs when interacting with the tables I have. For example, when I click on either the graph or any of the tables, the graph becomes very large, occupying the entire screen. As shown in the image below:

When I leave the screen split with Console, the graph is rendered responsively, as I change the screen size the size of the graph is also changed, however, if I leaveConsole the graph remains occupying the entire the screen and does not return to the default initial size shown in the first image.

Does anyone know how to tell me how to fix these bugs? I couldn't understand why this is happening.

Thnaks in advance.

var composite = dc.compositeChart('#composite');
var vendedorTable = dc.dataTable("#vendedores");
var citiesTable = dc.dataTable("#cities");

function remove_empty_bins(source_group) {
  return {
    top: function(N) {
      return source_group.all().filter(function(d) {
        return d.value.totalAno > 1e-3 ||
          d.value.totalHomologo > 1e-3;
      }).slice(0, N);
    }
  };
}

var url = 'https://gist.githubusercontent.com/bernalvinicius/3cece295bc37de1697e7f83418e7fcc9/raw/a5820379ec6eae76ee792495cc5dd1685c977a73/vendedores.json';
d3.json(url).then(function(data) {

  data.forEach(d =>
    Object.assign(d, {
      mes: d.Month,
      atual: d.Vendas_Ano,
      passado: d.Vendas_Ant
    })
  );
  var cf = crossfilter(data);

  vendedorDim = cf.dimension(function(d) {
    return d.vendnm;
  });
  var vendedorGroup = vendedorDim.group().reduce(reduceAdd, reduceRemove, reduceInitial);

  citiesDim = cf.dimension(function(d) {
    return d.zona;
  });
  var citiesGroup = citiesDim.group().reduce(reduceAdd, reduceRemove, reduceInitial);

  var dim = cf.dimension(dc.pluck('mes')),
    grp1 = dim.group().reduceSum(dc.pluck('atual')),
    grp2 = dim.group().reduceSum(dc.pluck('passado'));
  var minMonth = dim.bottom(1)[0].mes;
  var maxMonth = dim.top(1)[0].mes;

  var all = cf.groupAll();

  dc.dataCount(".dc-data-count")
    .dimension(cf)
    .group(all);

  function reduceAdd(p, v) {
    p.totalAno += +v.Vendas_Ano;
    p.totalHomologo += +v.Vendas_Ant;
    return p;
  }

  function reduceRemove(p, v) {
    p.totalAno -= v.Vendas_Ano;
    p.totalHomologo -= v.Vendas_Ant;
    return p;
  }

  function reduceInitial() {
    return {
      totalAno: 0,
      totalHomologo: 0,
    };
  }

  // Fake Dimension
  rank = function(p) {
    return ""
  };

  // Chart by months
  composite
    .width(600)
    .height(300)
    .x(d3.scaleLinear().domain([1, 12]))
    .yAxisLabel("")
    .xAxisLabel("Month")
    .legend(dc.legend().x(500).y(0).itemHeight(13).gap(5))
    .renderHorizontalGridLines(true)
    .compose([
      dc.lineChart(composite)
      .dimension(dim)
      .colors('steelblue')
      .group(grp1, "Currently Year"),
      dc.lineChart(composite)
      .dimension(dim)
      .colors('darkorange')
      .group(grp2, "Last Year")
    ])
    .brushOn(true);

  composite.brush().extent([-0.5, data.length + 1.5])
  composite.extendBrush = function(brushSelection) {
    if (brushSelection) {
      vendedorTable.filter(null);
      vendedorDim.filter(null);
      citiesTable.filter(null);
      citiesDim.filter(null);
      const point = Math.round((brushSelection[0] + brushSelection[1]) / 2);
      return [
        point - 0.5,
        point + 0.5
      ];
    }
  };

  // Sales Table
  vendedorTable.width(500)
    .height(480)
    .dimension(remove_empty_bins(vendedorGroup))
    .group(rank)
    .columns([function(d) {
        return d.key;
      },
      function(d) {
        return Number(Math.round(d.value.totalAno * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      },
      function(d) {
        return Number(Math.round(d.value.totalHomologo * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      }
    ])
    .sortBy(function(d) {
      return d.value.totalAno
    })
    .order(d3.descending)

  // Cities Table
  citiesTable.width(500)
    .height(480)
    .dimension(remove_empty_bins(citiesGroup))
    .group(rank)
    .columns([function(d) {
        return d.key;
      },
      function(d) {
        return Number(Math.round(d.value.totalAno * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      },
      function(d) {
        return Number(Math.round(d.value.totalHomologo * 100) / 100).toLocaleString("es-ES", {
          minimumFractionDigits: 2
        }) + '€';
      }
    ])
    .sortBy(function(d) {
      return d.value.totalAno
    })
    .order(d3.descending)

  // Sales click events
  vendedorTable.on('pretransition', function(table) {
    table.selectAll('td.dc-table-column')
      .on('click', function(d) {
        let filters = table.filters().slice();
        if (filters.indexOf(d.key) === -1)
          filters.push(d.key);
        else
          filters = filters.filter(k => k != d.key);
        if (filters.length === 0)
          vendedorDim.filter(null);
        else
          vendedorDim.filterFunction(function(d) {
            return filters.indexOf(d) !== -1;
          })
        table.replaceFilter([filters]);

        citiesTable.filter(null);
        citiesDim.filter(null);
        composite.filter(null);

        dc.redrawAll();
      });
    let filters = table.filters();
    table.selectAll('tr.dc-table-row')
      .classed('sel-rows', d => filters.indexOf(d.key) !== -1);
  });

  // Cities click events
  citiesTable.on('pretransition', function(table) {
    table.selectAll('td.dc-table-column')
      .on('click', function(d) {
        let filters = table.filters().slice();
        if (filters.indexOf(d.key) === -1)
          filters.push(d.key);
        else
          filters = filters.filter(k => k != d.key);
        if (filters.length === 0)
          citiesDim.filter(null);
        else
          citiesDim.filterFunction(function(d) {
            return filters.indexOf(d) !== -1;
          })
        table.replaceFilter([filters]);

        vendedorTable.filter(null);
        vendedorDim.filter(null);
        composite.filter(null);

        dc.redrawAll();
      });
    let filters = table.filters();
    table.selectAll('tr.dc-table-row')
      .classed('sel-rows', d => filters.indexOf(d.key) !== -1);
  });

  dc.renderAll();

  // reset functions
  $('#reset').on('click', function() {
    vendedorTable.filter(null);
    vendedorDim.filter(null);
    citiesTable.filter(null);
    citiesDim.filter(null);
    composite.filter(null);

    dc.redrawAll();
  });

  $('#resetTable').on('click', function() {
    vendedorTable.filter(null);
    vendedorDim.filter(null);
    citiesTable.filter(null);
    citiesDim.filter(null);
    composite.filter(null);

    dc.redrawAll();
  });

  $('#resetTable2').on('click', function() {
    vendedorTable.filter(null);
    vendedorDim.filter(null);
    citiesTable.filter(null);
    citiesDim.filter(null);
    composite.filter(null);

    dc.redrawAll();
  });

  /****************************************************************************/
  // Functions to handle responsive

  var adjustX = 10,
    adjustY = 40;

  apply_resizing(composite, adjustX, adjustY, function(composite) {
    composite.legend().x(window.innerWidth - 200);
  });

  var find_query = function() {
    var _map = window.location.search.substr(1).split('&').map(function(a) {
      return a.split('=');
    }).reduce(function(p, v) {
      if (v.length > 1)
        p[v[0]] = decodeURIComponent(v[1].replace(/\+/g, " "));
      else
        p[v[0]] = true;
      return p;
    }, {});
    return function(field) {
      return _map[field] || null;
    };
  }();

  var resizeMode = find_query('resize') || 'widhei';

  function apply_resizing(composite, adjustX, adjustY, onresize) {
    if (resizeMode === 'viewbox') {
      composite
        .width(300)
        .height(200)
        .useViewBoxResizing(true);
      d3.select(composite.anchor()).classed('fullsize', false);
    } else {
      adjustX = adjustX || 0;
      adjustY = adjustY || adjustX || 0;
      composite
        .width(window.innerWidth - adjustX)
        .height(window.innerHeight - adjustY);
      window.onresize = function() {
        if (onresize) {
          onresize(composite);
        }
        composite
          .width(window.innerWidth - adjustX)
          .height(window.innerHeight - adjustY);

        if (composite.rescale) {
          composite.rescale();
        }
        composite.redraw();
      };
    }
  }
});

#composite {
  padding: 10px;
}

.dc-table-group {
  visibility: collapse;
}

tr.dc-table-row.sel-rows {
  background-color: lightblue;
}

.brush .custom-brush-handle {
  display: none;
}

<link rel="shortcut icon" href="https://img.icons8.com/nolan/64/puzzle.png">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dc/2.1.8/dc.css">

<title>12</title>

            Fictitious company data | Drilldown Example |

                             selected from
             records |
             Reset

                Sales
                Current Year
                Last Year

                City
                Current Year
                Last Year

Body:
Thanks for posting an example! The bug doesn't show up in the SO code snippet feature unless you go to full page mode. I found your fiddle easier to work with.

Note: this is a complete rewrite of my previous answer, which was not clear.

1. Using ResizeObserver

updated 4/28/20

As of Safari 13.1 (released March 24 2020) all modern browsers support ResizeObserver. This is the cleanest way to detect chart resizing.

I recommend

Use a top-down layout such as flexbox or grid to position the  divs for your charts

Use ResizeObserver to determine when the div has changed size

Tell the charts to detect the chart div size using .width(null).height(null)

There is currently one resizing example that does this.

The special value null tells the chart to make the SVG node the same size as its parent div:

chart1.width(null)
    .height(null)

The callback uses a helper function to disable transitions, because transitions just slow resizing down and make it look clunky:

const callback = chart => entries => {
    redraw_chart_no_transitions(
        chart
            .width(null)
            .height(null)
            .rescale());
    };

Setting up the observer looks like

new ResizeObserver(callback(chart1)).observe(d3.select('#test1').node());

Please see the example for more details.

2. Using window.onresize

The other resizing examples watch for window.onresize because until recently that was the only efficient, reliable cross-browser way to detect changes.

They calculate chart sizes based on the window size, which works well if your layout is bottom-up, e.g. using the default float: left layout.

Here is the function which sets this up:

function apply_resizing(chart, adjustX, adjustY, onresize) {
    if(!Array.isArray(chart))
        chart = [chart];
    if(!isNaN(adjustX))
        adjustX = (dx => x => x-dx)(adjustX);
    adjustX = adjustX || (x => x);
    if(!isNaN(adjustY))
        adjustY = (dy => y => y-dy)(adjustY);
    adjustY = adjustY || adjustX || (y => y);
    chart.forEach(c => c.width(adjustX(window.innerWidth))
                  .height(adjustY(window.innerHeight)));
    window.onresize = function () {
        if (onresize) {
            chart.forEach(onresize);
        }
        chart.forEach(c => {
            c.width(adjustX(window.innerWidth))
                .height(adjustY(window.innerHeight));
            if (c.rescale) {
                c.rescale();
            }
        });
        redraw_chart_no_transitions(chart);
    };
}

A single chart can be initialized like so:

apply_resizing(chart, 20);

This fills the window but makes the chart 20 pixels less wide.

The function can also take multiple charts in an array, and adjustment functions to support complicated layouts, like one where two charts should split the window vertically:

apply_resizing([heatmapChart, barChart], 20, y => y/2-fudge);


问:
How to send props in class component to functional component?
I am beginner to reactjs. need to know how to send the props values in one page to another page. Props are on the first page I can get the class component value how to get the values in another page. Thanks in advance

wallcolor.jsx

```<code>import React, { Component } from "react";
import { SketchPicker } from 'react-color';
import WallFactory from "../../wall-factory-3d";
export default class WallColor extends Component {

  constructor(props) {
    super(props);
    this.state = {
        background: '#d3d3d3',
    };
  }

 handleChangeComplete(e){
    this.setState({ background: e.hex },()=>{
        return <WallFactory background={this.state.background}/>
    });
  };

  render() {
    return (
  <SketchPicker color={ this.state.background } onChangeComplete={(e)=>this.handleChangeComplete(e)}  />
  );
  }
}
</code>```

Another page is wall-factory-3d.js

```<code>import  { handleChangeComplete } from "../../components/toolbar/wallcolor";
import * as SharedStyle from '../../shared-style';

 function get_color(props){
   console.log(props.background);
}
</code>```

I tried this but not get output.

答:
Actually your child component will get mounted, as soon as your current component is rendered. So whatever the value after the render will not affect the previously rendered child component.

```<code>this.state = {
    backgroundColor: 'aqua';
}
</code>```

So <WallFactory background={this.state.background}/> will contain aqua.

If you need to pass a different background to the child, pass a function to the child like

```<code><WallFactory getBackgroundColor={this.passbackgroundColor}/>

passbackgroundColor() {
    return this.state.backgroundColor
}
</code>```

in the child component

```<code>const backgroundColor = props.getBackgroundColor();
</code>```

if you really need this to be dynamic.

Body:
I am beginner to reactjs. need to know how to send the props values in one page to another page. Props are on the first page I can get the class component value how to get the values in another page. Thanks in advance

wallcolor.jsx

import React, { Component } from "react";
import { SketchPicker } from 'react-color';
import WallFactory from "../../wall-factory-3d";
export default class WallColor extends Component {

  constructor(props) {
    super(props);
    this.state = {
        background: '#d3d3d3',
    };
  }

 handleChangeComplete(e){
    this.setState({ background: e.hex },()=>{
        return <WallFactory background={this.state.background}/>
    });
  };

  render() {
    return (
  <SketchPicker color={ this.state.background } onChangeComplete={(e)=>this.handleChangeComplete(e)}  />
  );
  }
}

Another page is wall-factory-3d.js

import  { handleChangeComplete } from "../../components/toolbar/wallcolor";
import * as SharedStyle from '../../shared-style';

 function get_color(props){
   console.log(props.background);
}

I tried this but not get output.

Body:
Actually your child component will get mounted, as soon as your current component is rendered. So whatever the value after the render will not affect the previously rendered child component.

this.state = {
    backgroundColor: 'aqua';
}

So <WallFactory background={this.state.background}/> will contain aqua.

If you need to pass a different background to the child, pass a function to the child like

<WallFactory getBackgroundColor={this.passbackgroundColor}/>

passbackgroundColor() {
    return this.state.backgroundColor
}

in the child component

const backgroundColor = props.getBackgroundColor();

if you really need this to be dynamic.


问:
Pause and Continue a Loop When Press Key in Python
Who can help me on this?

Pause Countdown when press "P" Key and continue the Countdown when press "S" key. Until now i have this code, but i cant find the way to solve this.

Thanks

```<code>from multiprocessing import Process
import keyboard
import time

def countdown_1():
    i=6
    j=40
    k=0
    while True:
        a = keyboard.read_key()

        if(str(a) != "p"):
            if(j==-1):
                j=59
                i -=1
            if(j > 9):

                print(str(k)+str(i)+":"+str(j))
            else:

                print(str(k)+str(i)+":"+str(k)+str(j))

            time.sleep(1)
            j -= 1
            if(i==0 and j==-1):
                break
    if(i==0 and j==-1):
        print("END")
        time.sleep(1)

countdown_1()
</code>```

答:
I get a solution to your problem, that is because when you use keyboard.readkey() python wait for a key to be pressed. instead, you should use keyboard.is_pressed('X')

I have modified your code to make a working version, I slightly change it to match my taste.

```<code>from multiprocessing import Process
import keyboard
import time

def countdown_1():
    pause_keyboard = False  # I use a bolean as a state is clearer for me
    i = 6  # minutes
    j = 40
    k = 0  # represent 0 we will instead use code format

    while True:

        starting_time = time.time()

        while True:  # this loop wait one second or slightly more

            if time.time() - starting_time >= 1: #  a second or more
                break

            if keyboard.is_pressed('p'):
                pause_keyboard = True

            elif keyboard.is_pressed('s'):
                pause_keyboard = False

        if pause_keyboard:
            continue

        if (j == -1): ## here we adjust the count when we changes minutes

            j = 59  # 59 secondes
            i -= 1  # one minutes less

        if(j > 9):  ## in order to pretty print

            print("{}{}:{}".format(0, i, j))  # you can direclty use 0 instead of k.
        else:
            print("{}{}:{}{}".format(0, i, 0, j))

        j -= 1

        if(i==0 and j==-1):  # we finish the counter
            break

    if(i==0 and j==-1):
        print("END")
        time.sleep(1) # wait a last second

countdown_1()
</code>```

EDIT: Use time.time() instead of sleep to be able to catch signals.

Body:
Who can help me on this?

Pause Countdown when press "P" Key and continue the Countdown when press "S" key. Until now i have this code, but i cant find the way to solve this.

Thanks

from multiprocessing import Process
import keyboard
import time

def countdown_1():
    i=6
    j=40
    k=0
    while True:
        a = keyboard.read_key()

        if(str(a) != "p"):
            if(j==-1):
                j=59
                i -=1
            if(j > 9):

                print(str(k)+str(i)+":"+str(j))
            else:

                print(str(k)+str(i)+":"+str(k)+str(j))

            time.sleep(1)
            j -= 1
            if(i==0 and j==-1):
                break
    if(i==0 and j==-1):
        print("END")
        time.sleep(1)

countdown_1()

Body:
I get a solution to your problem, that is because when you use keyboard.readkey() python wait for a key to be pressed. instead, you should use keyboard.is_pressed('X')

I have modified your code to make a working version, I slightly change it to match my taste.

from multiprocessing import Process
import keyboard
import time

def countdown_1():
    pause_keyboard = False  # I use a bolean as a state is clearer for me
    i = 6  # minutes
    j = 40
    k = 0  # represent 0 we will instead use code format

    while True:

        starting_time = time.time()

        while True:  # this loop wait one second or slightly more

            if time.time() - starting_time >= 1: #  a second or more
                break

            if keyboard.is_pressed('p'):
                pause_keyboard = True

            elif keyboard.is_pressed('s'):
                pause_keyboard = False

        if pause_keyboard:
            continue

        if (j == -1): ## here we adjust the count when we changes minutes

            j = 59  # 59 secondes
            i -= 1  # one minutes less

        if(j > 9):  ## in order to pretty print

            print("{}{}:{}".format(0, i, j))  # you can direclty use 0 instead of k.
        else:
            print("{}{}:{}{}".format(0, i, 0, j))

        j -= 1

        if(i==0 and j==-1):  # we finish the counter
            break

    if(i==0 and j==-1):
        print("END")
        time.sleep(1) # wait a last second

countdown_1()

EDIT: Use time.time() instead of sleep to be able to catch signals.


问:
How to interact with USSD menu?
I would like to write a program that would interact with an existing USSD service, so I need a way to dial the code, 'navigate' the menus,send additional commands and read any data. What would be a good way to achieve this?
I am open to any technology/platform at the moment.
I have looked into Android but there doesn't seem to be a USSD Api.
Thankx.</p>

答:
As far as I know it's currently it's impossible on Android: http://code.google.com/p/android/issues/detail?id=1285.

I left a comment that I need this feature and I hope some day Google will add this API.

But it's look like you can do it on winmo: sending USSD in C#?

Also you can try linux and usb modem - http://linux.softpedia.com/get/Communications/Telephony/gsm-ussd-57048.shtml

Title: How to interact with USSD menu?


问:
How do I keep the camera from changing its size?
I have attached two screenshots to my problem. Basically on resizing the Game view window the camera size also gets resized and the objects get moved when pressing play. How do I solve this?

答:
Your game view is set to "Free Aspect" that mean that you do not have a screen ratio set.

I would recommend to set set it to 16:9 or 16:10 if you make a "landscape" format game because most of the screens have this kind of ratio.

You can also define you own resolutions and test your game in different resolutions to have a preview of what your game will look like on a give screen resolution or ratio.

Free aspect is not a good choice because your camera can't scale at all.

Have a nice day


问:
How can jq read lines from a file and create valid a JSON?
I need help with creating a valid JSON file via jq which read lines from the file.

I have some text.txt file:

```<code>rabbit1-test1
rabbit1-test2
rabbit1-test3
</code>```

And the bash-script:

```<code>VHOSTNAME=/
NODENAME=node1

input="test.txt"
while IFS= read -r line; do jq -n \
                  --arg a "$VHOSTNAME" \
                  --arg b "$line"  \
                  --arg c "$NODENAME" \
                  '{"data": [{"{#VHOSTNAME}": $a, "{#QUEUENAME}": $b, "{#NODENAME}": $c}]}' ;done < "$input"
</code>```

But, when I run the script, the JSON isn't valid:

```<code>{
  "data": [
    {
      "{#VHOSTNAME}": "/",
      "{#QUEUENAME}": "rabbit1-test1",
      "{#NODENAME}": "node1"
    }
  ]
}
{
  "data": [
    {
      "{#VHOSTNAME}": "/",
      "{#QUEUENAME}": "rabbit1-test2",
      "{#NODENAME}": "node1"
    }
  ]
}
{
  "data": [
    {
      "{#VHOSTNAME}": "/",
      "{#QUEUENAME}": "rabbit1-test3",
      "{#NODENAME}": "node1"
    }
  ]
}
</code>```

I can't understand why jq reads file incorrectly.
Please help me.

答:
Why don't you use jq's split ?

```<code>jq -Rs --arg a '/' --arg c 'node1' '[ .[:-1] |
      split("\n")[] |
      { "{#VHOSTNAME}" : $a ,
        "{#QUEUENAME}": . ,
        "{#NODENAME}": $c } ] |
       { "data" : . }' sample.txt
</code>```

Out:

```<code>{
  "data": [
    {
      "{#VHOSTNAME}": "/",
      "{#QUEUENAME}": "rabbit1-test1",
      "{#NODENAME}": "node1"
    },
    {
      "{#VHOSTNAME}": "/",
      "{#QUEUENAME}": "rabbit1-test2",
      "{#NODENAME}": "node1"
    },
    {
      "{#VHOSTNAME}": "/",
      "{#QUEUENAME}": "rabbit1-test3",
      "{#NODENAME}": "node1"
    }
  ]
}
</code>```

Body:
I need help with creating a valid JSON file via jq which read lines from the file.

I have some text.txt file:

rabbit1-test1
rabbit1-test2
rabbit1-test3

And the bash-script:

VHOSTNAME=/
NODENAME=node1

input="test.txt"
while IFS= read -r line; do jq -n \
                  --arg a "$VHOSTNAME" \
                  --arg b "$line"  \
                  --arg c "$NODENAME" \
                  '{"data": [{"{#VHOSTNAME}": $a, "{#QUEUENAME}": $b, "{#NODENAME}": $c}]}' ;done < "$input"

But, when I run the script, the JSON isn't valid:

{
  "data": [
    {
      "{#VHOSTNAME}": "/",
      "{#QUEUENAME}": "rabbit1-test1",
      "{#NODENAME}": "node1"
    }
  ]
}
{
  "data": [
    {
      "{#VHOSTNAME}": "/",
      "{#QUEUENAME}": "rabbit1-test2",
      "{#NODENAME}": "node1"
    }
  ]
}
{
  "data": [
    {
      "{#VHOSTNAME}": "/",
      "{#QUEUENAME}": "rabbit1-test3",
      "{#NODENAME}": "node1"
    }
  ]
}

I can't understand why jq reads file incorrectly.
Please help me.

Body:
Why don't you use jq's split ?

jq -Rs --arg a '/' --arg c 'node1' '[ .[:-1] |
      split("\n")[] |
      { "{#VHOSTNAME}" : $a ,
        "{#QUEUENAME}": . ,
        "{#NODENAME}": $c } ] |
       { "data" : . }' sample.txt

Out:

{
  "data": [
    {
      "{#VHOSTNAME}": "/",
      "{#QUEUENAME}": "rabbit1-test1",
      "{#NODENAME}": "node1"
    },
    {
      "{#VHOSTNAME}": "/",
      "{#QUEUENAME}": "rabbit1-test2",
      "{#NODENAME}": "node1"
    },
    {
      "{#VHOSTNAME}": "/",
      "{#QUEUENAME}": "rabbit1-test3",
      "{#NODENAME}": "node1"
    }
  ]
}


问:
How to maximize browser window using puppeteer?
I am trying to maximize the browser window using puppeteer. I tried below code but the browser is not maximized to full mode. I also did not find any function available in puppeteer library to maximize the window.

(async () => {
  const browser = await puppeteer.launch({headless: false , slowMo: 100, rgs: ['--start-fullscreen', '--window-size=1920,1080'], executablePath: 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe' });
  const page = await browser.newPage();

  await page.setViewport({ width: 1920, height: 1080 });
```

答: In my case helped defaultViewport: null

Body: In my case helped defaultViewport: null