问:
Gradle: Uber Jar creation fails with "Could not expand ZIP"
I'm trying to create a Fat/Uber jar using Gradle.  Unfortunately, I keep running into the following error:

```<code>> Task :fatJar FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':fatJar'.
> Could not expand ZIP '/home/me/.gradle/caches/modules-2/files-2.1/org.apache.drill/drill-client/1.13.0/c90c87887c292a3712eccc7cebdc48b0b9d93ec9/drill-client-1.13.0.pom'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/4.9/userguide/command_line_interface.html#sec:command_line_warnings
</code>```

I have tried deleting my cache directory thinking maybe something was corrupted, but still no joy.

build.gradle file:

```<code>apply plugin: 'java'
apply plugin: 'maven'

group = 'com.me.ps'
version = me.version

sourceCompatibility = 1.8
targetCompatibility = 1.8

buildscript {
    repositories {
        jcenter()
    }
}

repositories {
     [...]
}

dependencies {
    // Explicityly added to in hopes of being included in the fat jar
    compile group: 'org.apache.hadoop', name: 'hadoop-common', version: '2.7.0-me-1803'

    // dependencies listed in the pom.xml
    compile group: 'com.me.ojai', name: 'me-ojai-driver', version: '6.0.1-me'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.6.5'
    compile group: 'org.apache.kafka', name: 'connect-json', version: '1.0.1-me-1803-streams-6.0.1'
    compile group: 'org.apache.spark', name: 'spark-core_2.11', version: '2.2.1'
    compile group: 'org.apache.spark', name: 'spark-streaming_2.11', version: '2.2.1-me-1803'
    compile group: 'org.apache.spark', name: 'spark-streaming-kafka-0-10_2.11', version: '2.2.1-me-1803'
    compile group: 'org.apache.kafka', name: 'kafka-clients', version: '1.0.1-me-1803-streams-6.0.1'

    // dependencies not in the pom.xml, but added to make the gradle build work
    compile group: 'xerces', name: 'xercesImpl', version: '2.11.0'
    compile group: 'org.json', name: 'json', version: '20171018'
    compile group: 'com.google.guava', name: 'guava', version: '19.0'

}

task fatJar(type: Jar) {
    baseName = project.name + '-all'
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
    manifest {
        attributes 'Main-Class': 'org.Lol'
    }
}
</code>```

I have tried using the shadowJar plugin, but that has led to dependencies being not included in the fat jar.  I have a separate question regarding that issue.  Currently, I'm using Maven which builds a fat jar perfectly.

答: The latest release of the shadowJar plugin fixed the issue.</p>

Body:
I'm trying to create a Fat/Uber jar using Gradle.  Unfortunately, I keep running into the following error:

> Task :fatJar FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':fatJar'.
> Could not expand ZIP '/home/me/.gradle/caches/modules-2/files-2.1/org.apache.drill/drill-client/1.13.0/c90c87887c292a3712eccc7cebdc48b0b9d93ec9/drill-client-1.13.0.pom'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/4.9/userguide/command_line_interface.html#sec:command_line_warnings

I have tried deleting my cache directory thinking maybe something was corrupted, but still no joy.

build.gradle file:

apply plugin: 'java'
apply plugin: 'maven'

group = 'com.me.ps'
version = me.version

sourceCompatibility = 1.8
targetCompatibility = 1.8

buildscript {
    repositories {
        jcenter()
    }
}

repositories {
     [...]
}

dependencies {
    // Explicityly added to in hopes of being included in the fat jar
    compile group: 'org.apache.hadoop', name: 'hadoop-common', version: '2.7.0-me-1803'

    // dependencies listed in the pom.xml
    compile group: 'com.me.ojai', name: 'me-ojai-driver', version: '6.0.1-me'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.6.5'
    compile group: 'org.apache.kafka', name: 'connect-json', version: '1.0.1-me-1803-streams-6.0.1'
    compile group: 'org.apache.spark', name: 'spark-core_2.11', version: '2.2.1'
    compile group: 'org.apache.spark', name: 'spark-streaming_2.11', version: '2.2.1-me-1803'
    compile group: 'org.apache.spark', name: 'spark-streaming-kafka-0-10_2.11', version: '2.2.1-me-1803'
    compile group: 'org.apache.kafka', name: 'kafka-clients', version: '1.0.1-me-1803-streams-6.0.1'

    // dependencies not in the pom.xml, but added to make the gradle build work
    compile group: 'xerces', name: 'xercesImpl', version: '2.11.0'
    compile group: 'org.json', name: 'json', version: '20171018'
    compile group: 'com.google.guava', name: 'guava', version: '19.0'

}

task fatJar(type: Jar) {
    baseName = project.name + '-all'
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
    manifest {
        attributes 'Main-Class': 'org.Lol'
    }
}

I have tried using the shadowJar plugin, but that has led to dependencies being not included in the fat jar.  I have a separate question regarding that issue.  Currently, I'm using Maven which builds a fat jar perfectly.


来源: stackexchange

问:
Install Yarn Ubuntu 16.04 (Linux Mint 18.1)
I have a new installation of Linux Mint 18.1 with Ubuntu 16.04.
I have installed Node 6.10.0.

When doing the command that indicates the documentation of Yarn:

```<code>sudo apt-get update && sudo apt-get install yarn
</code>```

It says "could not find yarn package"

I must do something else, because in the documentation I do not see anything about it.

Thank you.

答: Be careful when using &&. I get the same error when running sudo apt-get update, which prevents terminal from running sudo apt-get install yarn.   I was able to successfully install yarn on Ubuntu 16.04 by running these commands separately (without using &&)

ContentLicense: CC BY-SA 3.0

Body:
I have a new installation of Linux Mint 18.1 with Ubuntu 16.04.
I have installed Node 6.10.0.

When doing the command that indicates the documentation of Yarn:

sudo apt-get update && sudo apt-get install yarn

It says "could not find yarn package"

I must do something else, because in the documentation I do not see anything about it.

Thank you.

ContentLicense: CC BY-SA 4.0


问:
Error Creating Project - 'where' is not recognized as an internal or external command, operable program or batch file
I just installed Android Studio on my Windows 10 System. I got some error related to Virtualization (for Android emulation as my virtualization was disabled), I enabled virtualization and restarted my PC. Then I installed Flutter and Dart's plugin. Now I am getting this error whenever I am trying to create a Flutter project in Android Studio - 'where' is not recognized as an internal or external command, operable program or batch file.

What I have tried -

Reinstalled Android Studio,
  Deleted folder related to Android Studio from user folder (ie. C:\Users\username)

What else should I try?

'where' is not recognized as an internal or external command, operable program or batch file.

答:
Make sure you put flutter in your path (the environment variables).Also make  sure you follow the flutter steps step by step:

Flutter Windows Steps


问:
Use jQuery to scroll up and down to div id
jQuery noob here. I have a fixed nav bar where I have an About div that I want to click on to scroll to the about section of the page. It's halfway working right now. If I am above the about section, clicking on the div will successfully scroll down to the about section, but if I choose to scroll past the about section it will not scroll back up to it if I click on the button. I am unsure about how to get it to scroll back up instead of only being able to go in one direction.

Here's my HTML:

```<code><nav>
  <div id="about-button">About</div>
  <div id="projects-button">Projects</div>
</nav>

<section class="about-me">
  <div class="about" id="about">
    <div class="about-box"><h1>About</h1></div>
      <div class="bio-box">
        <h3>Bio</h3>
        <p class="bio-text">Bio text yada yada.</p>
        <p class="bio-text">More bio text yada yada</p>
      </div>
    </div>
  </div>
</section>

<section class="projects-section">
  <div class="projects" id="projects">
     <div class="project-main"><h1>Projects</h1></div>
       <a class="project-link" href="">
         <div class="project-picture"></div>
       </a>
     <div class="project-title">Project Name</div>
  </div>
</section>
</code>```

And this is my jQuery:

```<code>function scrollToSection() {
 $("#about-button").click(function() {
    $('html, body').animate({
        scrollTop: $("#about").offset().top
    }, 2000);
 });
}

</code>```

答:
You don't need to use jQuery or JS.

Changing your nav elements to actual links should work.

```<code><div id="about-button">About</div>
<div id="projects-button">Projects</div>
</code>```

The code above should become...

```<code><a href='#about'>About</a>
<a href='#projects'>Projects</a>
</code>```

The a elements use the id values of your desired destination as their ultimate destinations.

Body:
jQuery noob here. I have a fixed nav bar where I have an About div that I want to click on to scroll to the about section of the page. It's halfway working right now. If I am above the about section, clicking on the div will successfully scroll down to the about section, but if I choose to scroll past the about section it will not scroll back up to it if I click on the button. I am unsure about how to get it to scroll back up instead of only being able to go in one direction.

Here's my HTML:

About

Projects

About

Bio

Bio text yada yada.

More bio text yada yada

Projects

Project Name

And this is my jQuery:

function scrollToSection() {
 $("#about-button").click(function() {
    $('html, body').animate({
        scrollTop: $("#about").offset().top
    }, 2000);
 });
}

Body:
You don't need to use jQuery or JS.

Changing your nav elements to actual links should work.

<div id="about-button">About</div>
<div id="projects-button">Projects</div>

The code above should become...

<a href='#about'>About</a>
<a href='#projects'>Projects</a>

The a elements use the id values of your desired destination as their ultimate destinations.


问:
Why Laravel 5.8 makes repeated queries to the database when working with the session
In Laravel 5.8, when working with a session, two extra queries to the database are performed compared to Laravel 5.7.

Laravel 5.7

```<code>select * from `sessions` where `id` = '00kaQxJLG6roUAp9DaCui7esa31sbthHqEzwW62H' limit 1
</code>```

Laravel 5.8

```<code>select * from `sessions` where `id` = 'anFc8QgnSpMbMVHcuxAldxKdLhNyo3IUNavylQTD' limit 1

update `sessions` set `payload` = 'YTozOntzOjY6Il90b2tlbiI7czo0MDoiQm12QlFHNzVNRVpZcTRkMWZwcmNMS2kwcm12czlvZkpXZUg0cFpEQyI7czo5OiJfcHJldmlvdXMiO2E6MTp7czozOiJ1cmwiO3M6MTY6Imh0dHA6Ly9kZXYubG9jYWwiO31zOjY6Il9mbGFzaCI7YToyOntzOjM6Im9sZCI7YTowOnt9czozOiJuZXciO2E6MDp7fX19', `last_activity` = 1559161593, `user_id` = '', `ip_address` = '127.0.0.1', `user_agent` = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/73.0.3683.86 Chrome/73.0.3683.86 Safari/537.36' where `id` = 'anFc8QgnSpMbMVHcuxAldxKdLhNyo3IUNavylQTD'

select * from `sessions` where `id` = 'anFc8QgnSpMbMVHcuxAldxKdLhNyo3IUNavylQTD' limit 1
</code>```

New installation. No packages.

答:
Resolved

In Laravel 5.8 middleware was changed

```<code>Illuminate/Session/Middleware/StartSession.php
</code>```

In method handle was added

```<code>$this->saveSession($request);
</code>```

if the session has been configured it updated in the database.

In Laravel 5.7 only in cookies.

Body:
In Laravel 5.8, when working with a session, two extra queries to the database are performed compared to Laravel 5.7.

Laravel 5.7

select * from `sessions` where `id` = '00kaQxJLG6roUAp9DaCui7esa31sbthHqEzwW62H' limit 1

Laravel 5.8

select * from `sessions` where `id` = 'anFc8QgnSpMbMVHcuxAldxKdLhNyo3IUNavylQTD' limit 1

update `sessions` set `payload` = 'YTozOntzOjY6Il90b2tlbiI7czo0MDoiQm12QlFHNzVNRVpZcTRkMWZwcmNMS2kwcm12czlvZkpXZUg0cFpEQyI7czo5OiJfcHJldmlvdXMiO2E6MTp7czozOiJ1cmwiO3M6MTY6Imh0dHA6Ly9kZXYubG9jYWwiO31zOjY6Il9mbGFzaCI7YToyOntzOjM6Im9sZCI7YTowOnt9czozOiJuZXciO2E6MDp7fX19', `last_activity` = 1559161593, `user_id` = '', `ip_address` = '127.0.0.1', `user_agent` = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/73.0.3683.86 Chrome/73.0.3683.86 Safari/537.36' where `id` = 'anFc8QgnSpMbMVHcuxAldxKdLhNyo3IUNavylQTD'

select * from `sessions` where `id` = 'anFc8QgnSpMbMVHcuxAldxKdLhNyo3IUNavylQTD' limit 1

New installation. No packages.

Body:
Resolved

In Laravel 5.8 middleware was changed

Illuminate/Session/Middleware/StartSession.php

In method handle was added

$this->saveSession($request);

if the session has been configured it updated in the database.

In Laravel 5.7 only in cookies.


问:
UnhandledPromiseRejectionWarning NodeJS
I am trying to fix my error but I don't know how I can fix it. I have searched arround the internet and tried some solutions like this Node UnhandledPromiseRejectionWarning but I didn't manage to fix it.

This is my error

And this is my code

```<code>var express = require('express')
var session = require('express-session')
var bodyParser = require('body-parser')
var request = require('request-promise')
var mongoose = require('mongoose')

require('dotenv').config()

mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true })

var citySchema = new mongoose.Schema({
    name: String
})

var cityModel = mongoose.model('City', citySchema)

async function collectWeather(cities) {
    var weatherData = []
    for (var city_object of cities) {
        var city = city_object.name
        var url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=e`
        request(url)
        var body = await request(url)
        var weatherJSON = JSON.parse(body)
        var weather = {
        city: city,
        temperature: Math.round(weatherJSON.main.temp),
        description: weatherJSON.weather[0].description,
        icon: weatherJSON.weather[0].icon,
        }
        weatherData.push(weather)
    }
    return weatherData
}

express()
    .use(express.static('static'))
    .use(bodyParser.urlencoded({extended: true}))
    .use(session({
        resave: false,
        saveUninitialized: true,
        secret: process.env.SESSION_SECRET
    }))

    .set('view engine', 'ejs')
    .set('views', 'view')

    .get('/', function(req, res) {
        cityModel.find({}, function(err, cities) {
            collectWeather(cities).then(function(result) {
                var weatherData = {weatherData: result}
                res.render('index', weatherData)
            })
        })
    })

    .post('/', function(req, res) {
        var newCity = new cityModel({name: req.body.city_name})
        newCity.save()
        res.redirect('/')
    })

    .listen(4000)
</code>```

I am still a beginner with node.js.

Thank you in advance.

答:
In addition to Rami's answer, you should fix newCity.save() operation. Mongoose save() return thenables. So you should handle save like this:

```<code>post('/', function(req, res) {
    var newCity = new cityModel({name: req.body.city_name})
    newCity.save()
    .then(result => {
        res.redirect('/')
    })
    .catch(err => {
        // handle error
        console.log(err);
        // render an error page for example.
    });
});
</code>```

Title: UnhandledPromiseRejectionWarning NodeJS

Body:
I am trying to fix my error but I don't know how I can fix it. I have searched arround the internet and tried some solutions like this Node UnhandledPromiseRejectionWarning but I didn't manage to fix it.

This is my error

And this is my code

var express = require('express')
var session = require('express-session')
var bodyParser = require('body-parser')
var request = require('request-promise')
var mongoose = require('mongoose')

require('dotenv').config()

mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true })

var citySchema = new mongoose.Schema({
    name: String
})

var cityModel = mongoose.model('City', citySchema)

async function collectWeather(cities) {
    var weatherData = []
    for (var city_object of cities) {
        var city = city_object.name
        var url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=e`
        request(url)
        var body = await request(url)
        var weatherJSON = JSON.parse(body)
        var weather = {
        city: city,
        temperature: Math.round(weatherJSON.main.temp),
        description: weatherJSON.weather[0].description,
        icon: weatherJSON.weather[0].icon,
        }
        weatherData.push(weather)
    }
    return weatherData
}

express()
    .use(express.static('static'))
    .use(bodyParser.urlencoded({extended: true}))
    .use(session({
        resave: false,
        saveUninitialized: true,
        secret: process.env.SESSION_SECRET
    }))

    .set('view engine', 'ejs')
    .set('views', 'view')

    .get('/', function(req, res) {
        cityModel.find({}, function(err, cities) {
            collectWeather(cities).then(function(result) {
                var weatherData = {weatherData: result}
                res.render('index', weatherData)
            })
        })
    })

    .post('/', function(req, res) {
        var newCity = new cityModel({name: req.body.city_name})
        newCity.save()
        res.redirect('/')
    })

    .listen(4000)

I am still a beginner with node.js.

Thank you in advance.

Body:
In addition to Rami's answer, you should fix newCity.save() operation. Mongoose save() return thenables. So you should handle save like this:

post('/', function(req, res) {
    var newCity = new cityModel({name: req.body.city_name})
    newCity.save()
    .then(result => {
        res.redirect('/')
    })
    .catch(err => {
        // handle error
        console.log(err);
        // render an error page for example.
    });
});


问:
How to link OpenFST to tensorflow custom op?
I'm trying to compile a tensorflow custom op that requires OpenFST (http://www.openfst.org/twiki/bin/view/FST/WebHome). However, I'm running into compilation errors where I run:

import tensorflow as tf
decoder_op = tf.load_op_library('./libfst_decoder.so')
```

<p>and get an undefined symbol error <code>undefined symbol: _ZN3fst21ConvertToLegalCSymbolEPSs</code>, so it's not able to find the linked object.</p>

<p>This is the CMake file I'm using:</p>

```cmake_minimum_required(VERSION 3.5)

execute_process(COMMAND python3 -c "import tensorflow; print(tensorflow.sysconfig.get_include())" OUTPUT_VARIABLE Tensorflow_INCLUDE_DIRS)

set (CMAKE_CXX_FLAGS "--std=c++11 -fPIC -O2 -D_GLIBCXX_USE_CXX11_ABI=0")

link_directories("/miniconda/envs/py36/lib/python3.6/site-packages/tensorflow")
include_directories(${Tensorflow_INCLUDE_DIRS})
include_directories("/usr/local/include")
add_library(fst_decoder SHARED fst_decoder.cc simple_decoder.cc)
target_link_libraries(fst_decoder -ltensorflow_framework -lfst -ldl -lm)
```

Are there any obvious issues with the CMake file to include an external library? Don't have too much experience with compiling C++.

答:
Solution is to recompile OpenFST with:
make CFLAGS='-D_GLIBCXX_USE_CXX11_ABI=0 -std=c++11' CXXFLAGS='-D_GLIBCXX_USE_CXX11_ABI=0 -std=c++11'
as tensorflow uses D_GLIBCXX_USE_CXX11_ABI=0.

Body:
I'm trying to compile a tensorflow custom op that requires OpenFST (http://www.openfst.org/twiki/bin/view/FST/WebHome). However, I'm running into compilation errors where I run:

import tensorflow as tf
decoder_op = tf.load_op_library('./libfst_decoder.so')

and get an undefined symbol error undefined symbol: _ZN3fst21ConvertToLegalCSymbolEPSs, so it's not able to find the linked object.

This is the CMake file I'm using:

cmake_minimum_required(VERSION 3.5)

execute_process(COMMAND python3 -c "import tensorflow; print(tensorflow.sysconfig.get_include())" OUTPUT_VARIABLE Tensorflow_INCLUDE_DIRS)

set (CMAKE_CXX_FLAGS "--std=c++11 -fPIC -O2 -D_GLIBCXX_USE_CXX11_ABI=0")

link_directories("/miniconda/envs/py36/lib/python3.6/site-packages/tensorflow")
include_directories(${Tensorflow_INCLUDE_DIRS})
include_directories("/usr/local/include")
add_library(fst_decoder SHARED fst_decoder.cc simple_decoder.cc)
target_link_libraries(fst_decoder -ltensorflow_framework -lfst -ldl -lm)

Are there any obvious issues with the CMake file to include an external library? Don't have too much experience with compiling C++.


答:
NodeJS uses asynchronous, non-blocking calls instead of using multiple threads.  It does this (at least in part) by using Promises.  A Promise is an object that represents something that will finish later.

On the line

```<code>        var body = await request(url)
</code>```

the call request(url) returns a promise, and the use of await causes the rest of the function to be deferred until the promise is resolved.

If the request fails, the Promise is rejected instead.  You could handle this case by using the .catch(callback) method of the Promise returned by request(url).

There may be other ways to do this, but I am not aware of them as have not used async/await notation.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

Title: UnhandledPromiseRejectionWarning NodeJS

Body:
NodeJS uses asynchronous, non-blocking calls instead of using multiple threads.  It does this (at least in part) by using Promises.  A Promise is an object that represents something that will finish later.

On the line

        var body = await request(url)

the call request(url) returns a promise, and the use of await causes the rest of the function to be deferred until the promise is resolved.

If the request fails, the Promise is rejected instead.  You could handle this case by using the .catch(callback) method of the Promise returned by request(url).

There may be other ways to do this, but I am not aware of them as have not used async/await notation.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await


问:
How can I sort List<Object> CRUD Repository
I'm trying to build simple REST for purchases I need 2 methods. The first method should show all purchases sorted by date. The second one removes all purchases for specified date I made a method to add and to get all purchases. Now I'm stuck.

```<code>@Entity
@Table (name="purchase")
public class Purchase {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "name")
private String name;

@CreationTimestamp
@Temporal(TemporalType.DATE)
@Column(name="createat")
private Date created;

@Column(name="price")
private BigDecimal price;

@Column(name="currency")
private String currency;
@Repository
public interface PurchaseRepository extends JpaRepository<Purchase, Long>
{
}

@Service
public class PurchaseService {

@Autowired
private PurchaseRepository purchaseRepository;

public void addPurchase(Purchase purchase) {
    purchaseRepository.save(purchase);
}

public List<Purchase> getAllPurchase() {

    List<Purchase> purchase = new ArrayList<>();
    purchaseRepository.findAll().forEach(purchase::add);
    return purchase;
}
}

@RestController
public class PurchaseController {

@Autowired
private PurchaseService purchaseService;

@PostMapping("/purchase")
public void addPurchase(@RequestBody Purchase purchase) {
    purchaseService.addPurchase(purchase);
}

@RequestMapping("/purchase")
public List<Purchase> getAllTopics() {
    return purchaseService.getAllPurchase();
}
}
</code>```

What I need:
1. method to sort my List sorted by date
2. method that removes all purchases for specified date

答:
You can use Spring Data JPA features in these cases.

Add the following methods to PurchaseRepository:

List<Purchase> findAllByOrderByCreatedAsc();

long deleteByCreated(Date created);

And after all, Spring is going to generate an appropriate query based on a method name.

Body:
I'm trying to build simple REST for purchases I need 2 methods. The first method should show all purchases sorted by date. The second one removes all purchases for specified date I made a method to add and to get all purchases. Now I'm stuck.

@Entity
@Table (name="purchase")
public class Purchase {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "name")
private String name;

@CreationTimestamp
@Temporal(TemporalType.DATE)
@Column(name="createat")
private Date created;

@Column(name="price")
private BigDecimal price;

@Column(name="currency")
private String currency;
@Repository
public interface PurchaseRepository extends JpaRepository<Purchase, Long>
{
}

@Service
public class PurchaseService {

@Autowired
private PurchaseRepository purchaseRepository;

public void addPurchase(Purchase purchase) {
    purchaseRepository.save(purchase);
}

public List<Purchase> getAllPurchase() {

    List<Purchase> purchase = new ArrayList<>();
    purchaseRepository.findAll().forEach(purchase::add);
    return purchase;
}
}

@RestController
public class PurchaseController {

@Autowired
private PurchaseService purchaseService;

@PostMapping("/purchase")
public void addPurchase(@RequestBody Purchase purchase) {
    purchaseService.addPurchase(purchase);
}

@RequestMapping("/purchase")
public List<Purchase> getAllTopics() {
    return purchaseService.getAllPurchase();
}
}

What I need:
1. method to sort my List sorted by date
2. method that removes all purchases for specified date


问:
Problem with jquery button click
I am facing a problem in the jquery click event.

My web page involves creating a button through javascript and assigning a class to the button ( call it A ). Now I want to detect the click of that button and I have written the following code for it :

```
 $(".A").click( function () {

    // do something

 });
```

To my surprise, this click event never gets called.

But when I make the button statically on the webpage ( during design time ), the same code works.

Is there a different approach to bind a button click with jquery in case a button is created dynamically?

答:
Your event handler fires at page load, before your button exists.

Either reset the event handler after you create the button, or use .live for late-binding:

```<code>$(".A").live('click', function () {
   // do something
});
</code>```

Now the handler will apply to .A even created in the future.

Title: Problem with jquery button click

Body:
I am facing a problem in the jquery click event.

My web page involves creating a button through javascript and assigning a class to the button ( call it A ). Now I want to detect the click of that button and I have written the following code for it :

 $(".A").click( function () {

    // do something

 });

To my surprise, this click event never gets called.

But when I make the button statically on the webpage ( during design time ), the same code works.

Is there a different approach to bind a button click with jquery in case a button is created dynamically?

Body:
Your event handler fires at page load, before your button exists.

Either reset the event handler after you create the button, or use .live for late-binding:

$(".A").live('click', function () {
   // do something
});

Now the handler will apply to .A even created in the future.


问:
Set selected drop down value from database in razor view MVC
I am explicitly creating a dropdownlist in razor mvc view. I would like the default option to be one of the items, the value of that item should come from database

View Code

```<code><div class="form-group">
  @Html.LabelFor(model => model[i].Customer.HomeType, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="SerivcesRegistrationInput col-md-10">
      @Html.DropDownListFor(model => model[i].Customer.HomeType, new List<SelectListItem>
 {
     new SelectListItem{ Text="House", Value = "House",@(Model[i].CustomerServices.HomeType == "House" ? Selected = true : false)  },
     new SelectListItem{ Text="Apartment", Value = "Apartment" },
     new SelectListItem{ Text="Farm", Value = "Farm" } },
      "Select your home type", htmlAttributes: new { @class = "form-control" })
 }
    </div>
</div>
</code>```

Controller Code

```<code> cs.HomeType = serviceDetails.HomeType;
 sp.CustomerServices = cs;
 return View("EditCustomerServices", ProviderList);
</code>```

Model has the data I need but how can I set it to correct Dropdown list value. I tried using short hand if but it gives me an error

```<code>Invalid member initializer
</code>```

Can I add if condition for Selected Boolean?

答:
@{
    var selected = Model.CustomerServices.HomeType == "House";
}

  @Html.LabelFor(model => model.Customer.HomeType, htmlAttributes: new { @class = "control-label col-md-2" })

      @Html.DropDownListFor(model => model.Customer.HomeType, new List<SelectListItem>
 {
     new SelectListItem{ Text="House", Value = "House", Selected = selected },
     new SelectListItem{ Text="Apartment", Value = "Apartment" },
     new SelectListItem{ Text="Farm", Value = "Farm" } },
      "Select your home type", htmlAttributes: new { @class = "form-control" })
 }

```

Body:
I am explicitly creating a dropdownlist in razor mvc view. I would like the default option to be one of the items, the value of that item should come from database

View Code

  @Html.LabelFor(model => model[i].Customer.HomeType, htmlAttributes: new { @class = "control-label col-md-2" })

      @Html.DropDownListFor(model => model[i].Customer.HomeType, new List<SelectListItem>
 {
     new SelectListItem{ Text="House", Value = "House",@(Model[i].CustomerServices.HomeType == "House" ? Selected = true : false)  },
     new SelectListItem{ Text="Apartment", Value = "Apartment" },
     new SelectListItem{ Text="Farm", Value = "Farm" } },
      "Select your home type", htmlAttributes: new { @class = "form-control" })
 }

Controller Code

 cs.HomeType = serviceDetails.HomeType;
 sp.CustomerServices = cs;
 return View("EditCustomerServices", ProviderList);

Model has the data I need but how can I set it to correct Dropdown list value. I tried using short hand if but it gives me an error

Invalid member initializer

Can I add if condition for Selected Boolean?

Body:
@{
    var selected = Model.CustomerServices.HomeType == "House";
}

<div class="form-group">
  @Html.LabelFor(model => model.Customer.HomeType, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="SerivcesRegistrationInput col-md-10">
      @Html.DropDownListFor(model => model.Customer.HomeType, new List<SelectListItem>
 {
     new SelectListItem{ Text="House", Value = "House", Selected = selected },
     new SelectListItem{ Text="Apartment", Value = "Apartment" },
     new SelectListItem{ Text="Farm", Value = "Farm" } },
      "Select your home type", htmlAttributes: new { @class = "form-control" })
 }
    </div>
</div>


问:
Google Cloud Dataflow: Dataflow programming model taking same computational time as it would take on a regular VM machine?
I am trying google cloud's dataflow service which is useful for efficient computation time. My code has the following programming model for the dataflow pipeline:

start=(p | "read" >> beam.io.ReadFromText("gcs path"))

  end= start | "data_generation" >> beam.Pardo(PerfromFunction)

What I am doing:

PerformFunction is a regular Python function which contains a few series of functions for data-generation purpose. My problem is that when I run this function on a regular VM of n1-standard-16 on a single processor, it takes around 1 hour to complete the whole process.

Why I opted Dataflow:

I then decided to go for Dataflow where a ParDo function performs Multi-Threading of the given function and obviously to reduce the computational time from 1 hour to less than 1 hour.

The Problem:

After running a Dataflow job with the above-mentioned programming model, I came to realize that Dataflow is still taking around 1 hour to complete the entire process which is mentioned as wall-time on the GCP Dataflow UI. I then logged in to the worker machine and saw the resource utilization using the command htop and found that the machine was only utilizing one processor with 60% average usage.

Expected Results or Suggestions:

1. Can multiprocessing be done in the Dataflow worker Cluster?

2. Is my programming model very limited and wrong?

3. ParDo function does not seem to reduce the computational time as expected, What do you think I am doing wrong here?

PS- Owing to some protocols, I can not share the code. Thank you for understanding. Also please correct me if I wrongly understand dataflow at some point.

答:
Apache Beam, and Dataflow are able to parallelize your computation based on the input that comes into it.

If you have a single computation to apply, and this computation takes one hour, then Beam will not be able to speed up your computation. Beam can help you if you need to apply the same computation multiple times to different elements (or data points).

You should also consider things such as overhead of running the computation in a distributed fashion (data copying, network calls, etc).

So, to be able to answer your question: How may individual "data points" (how many lines) are there in your GCS file? Is it possible to parallelize the computation over each one? How long does it take to process each one?


问:
Incomplete data: Delta source ended unexpectedly while git svn fetch
I have cloned my svn repo into git and everyday i am doing git svn fetch (i only do changes in SVN) but i am planning to move to git and i keep the git repo in sync for the day since the svn clone tooke me 2 weeks (yeah it's a big repo).

Anyway the git svn fetch has worked fine every day until 2 days ago where i now get

```<code>Incomplete data: Delta source ended unexpectedly at /usr/lib/perl5/site_perl/Git/SVN/Ra.pm line 290
</code>```

at a specific revision. I tried the different suggestions online about git svn reset and going back some revisions and i went about 20 revisions back with no luck. I also tried to run :

```<code>git config --get core.autocrlf
</code>```

which gave true.

I know that the svn repo is working good, i have no issues doing svn up.

Any ideas how i can get back on track to sync again ? I am stuck without ideas what to try.

I might reveal one issue. I don't recall but before running the issue i might have had a disk full on the disk where the repo is when i tried the fetch. Maybe that destroyed something ?

/donnib

答:
I resolved similar problem using -r param. My case was as follow:

I created /branches/dev branch in SVN  at particular revision, eg 1000 and started using it

all previous revision were made to /trunk

I started master branch migration with git svn clone, which got all svn /trunk to git master

then I've added another fetch config for my svn development branch and resumed the svn fetch

```<code># .git/config
[svn-remote "svn"]
    url = http://some-repo/path
    fetch = /trunk:refs/remotes/trunk
    fetch = branches/dev:refs/remotes/dev
</code>```

git svn fetch complained at revision 999, which belong to /trunk and has been already migrated to git master (Incomplete data: Delta source ended unexpectedly at /usr/lib/perl5/site_perl/Git/SVN/Ra.pm line 312)

notice error refers to line 312, which might be related to different problem than line 290 referred in this ticket?

then I run git svn fetch -r 1000:HEAD, which allowed me to migrate all revisions of /branches/dev excluding revisions before creating /branches/dev

Body:
I have cloned my svn repo into git and everyday i am doing git svn fetch (i only do changes in SVN) but i am planning to move to git and i keep the git repo in sync for the day since the svn clone tooke me 2 weeks (yeah it's a big repo).

Anyway the git svn fetch has worked fine every day until 2 days ago where i now get

Incomplete data: Delta source ended unexpectedly at /usr/lib/perl5/site_perl/Git/SVN/Ra.pm line 290

at a specific revision. I tried the different suggestions online about git svn reset and going back some revisions and i went about 20 revisions back with no luck. I also tried to run :

git config --get core.autocrlf

which gave true.

I know that the svn repo is working good, i have no issues doing svn up.

Any ideas how i can get back on track to sync again ? I am stuck without ideas what to try.

I might reveal one issue. I don't recall but before running the issue i might have had a disk full on the disk where the repo is when i tried the fetch. Maybe that destroyed something ?

/donnib

Body:
I resolved similar problem using -r param. My case was as follow:

I created /branches/dev branch in SVN  at particular revision, eg 1000 and started using it

all previous revision were made to /trunk

I started master branch migration with git svn clone, which got all svn /trunk to git master

then I've added another fetch config for my svn development branch and resumed the svn fetch

# .git/config
[svn-remote "svn"]
    url = http://some-repo/path
    fetch = /trunk:refs/remotes/trunk
    fetch = branches/dev:refs/remotes/dev

git svn fetch complained at revision 999, which belong to /trunk and has been already migrated to git master (Incomplete data: Delta source ended unexpectedly at /usr/lib/perl5/site_perl/Git/SVN/Ra.pm line 312)

notice error refers to line 312, which might be related to different problem than line 290 referred in this ticket?

then I run git svn fetch -r 1000:HEAD, which allowed me to migrate all revisions of /branches/dev excluding revisions before creating /branches/dev


问:
Is it possible to Decompile and read an SSIS package code?
I am working on a project which was owned by a different person. He created a job to update bunch of fields in handful of tables in SQL server. That job was based on an SSIS package. Now I have the DTSX file and the disabled job. When I tried to enable the job after changing the old credentials in the DTSX file, I am getting weird errors. I want to see the code behind the SSIS package and want to see how the update process is coded.
Is there a way to do this?</p>

答: Create a new solution and import the DTSX file into that. Visual Studio just serves as a glorified XML editor for SSIS packages.</p>


问:
Jest 'TypeError: is not a function' in jest.mock
I'm writing a Jest mock, but I seem to have a problem when defining a mocked function outside of the mock itself.

I have a class:

```<code>myClass.js

class MyClass {
  constructor(name) {
    this.name = name;
  }

  methodOne(val) {
    return val + 1;
  }

  methodTwo() {
    return 2;
  }
}

export default MyClass;
</code>```

And a file using it:

```<code>testSubject.js

import MyClass from './myClass';

const classInstance = new MyClass('Fido');

const testSubject = () => classInstance.methodOne(1) + classInstance.name;

export default testSubject;
</code>```

And the test:

```<code>testSubject.test.js

import testSubject from './testSubject';

const mockFunction = jest.fn(() => 2)

jest.mock('./myClass', () => () => ({
    name: 'Name',
    methodOne: mockFunction,
    methodTwo: jest.fn(),
}))

describe('MyClass tests', () => {
    it('test one', () => {
        const result = testSubject()

        expect(result).toEqual('2Name')
    })
})
</code>```

However, I get the following error:

TypeError: classInstance.methodOne is not a function

If I instead write:

```<code>...
methodOne: jest.fn(() => 2)
</code>```

Then the test passes no problem.

Is there a way of defining this outside of the mock itself?

答:
In my case, I had to mock a Node.js module. I'm using React and Redux in ES6, with Jest and Enzyme for unit tests.

In the file I'm using, and writing a test for, I'm importing the node modules as default:

```<code>import nodeModulePackage from 'nodeModulePackage';
</code>```

So I needed to mock it as a default since I kept getting the error (0, _blah.default) is not a function..

My solution was to do:

```<code>jest.mock('nodeModulePackage', () => jest.fn(() => {}));
</code>```

In my case, I just needed to override the function and make it return an empty object.

If you need to call a function on that node module, you'll do the following:

```<code>jest.mock('nodeModulePackage', () => ({ doSomething: jest.fn(() => 'foo') }));
</code>```

Body:
I'm writing a Jest mock, but I seem to have a problem when defining a mocked function outside of the mock itself.

I have a class:

myClass.js

class MyClass {
  constructor(name) {
    this.name = name;
  }

  methodOne(val) {
    return val + 1;
  }

  methodTwo() {
    return 2;
  }
}

export default MyClass;

And a file using it:

testSubject.js

import MyClass from './myClass';

const classInstance = new MyClass('Fido');

const testSubject = () => classInstance.methodOne(1) + classInstance.name;

export default testSubject;

And the test:

testSubject.test.js

import testSubject from './testSubject';

const mockFunction = jest.fn(() => 2)

jest.mock('./myClass', () => () => ({
    name: 'Name',
    methodOne: mockFunction,
    methodTwo: jest.fn(),
}))

describe('MyClass tests', () => {
    it('test one', () => {
        const result = testSubject()

        expect(result).toEqual('2Name')
    })
})

However, I get the following error:

TypeError: classInstance.methodOne is not a function

If I instead write:

...
methodOne: jest.fn(() => 2)

Then the test passes no problem.

Is there a way of defining this outside of the mock itself?

Body:
In my case, I had to mock a Node.js module. I'm using React and Redux in ES6, with Jest and Enzyme for unit tests.

In the file I'm using, and writing a test for, I'm importing the node modules as default:

import nodeModulePackage from 'nodeModulePackage';

So I needed to mock it as a default since I kept getting the error (0, _blah.default) is not a function..

My solution was to do:

jest.mock('nodeModulePackage', () => jest.fn(() => {}));

In my case, I just needed to override the function and make it return an empty object.

If you need to call a function on that node module, you'll do the following:

jest.mock('nodeModulePackage', () => ({ doSomething: jest.fn(() => 'foo') }));


问:
Python library for job scheduling, ssh
I'd like to find a user-space tool (preferably in Python - barring that, in anything I could easily modify if it doesn't already do what I need it to) to replace a short script I've been using that does the two things below:

polls less than 100 computers (Fedora 13, it so happens) for load, available memory, and if it looks like someone is using them

selects good hosts for jobs, runs these jobs over ssh.  These jobs are the execution of arbitrary command line programs which read and write to a shared filesystem - typically image processing scripts or similar - cpu, sometimes memory intensive tasks.

For example, using my current script, I can in a python prompt

```<code>>>> import hosts
>>> hosts.run_commands(['users']*5)
</code>```

or from the command line

```<code>% hosts.py "users" "users" "users" "users" "users"
</code>```

to run the command users 5 times (after finding 5 computers on which the command could be run by checking the cpu load and available memory on at least 5 computers from a config file).  There should be no job server other than the script I just ran, and no worker daemons or processes on the computers that will run these commands.

I'd additionally like to be able to track the jobs, run jobs again on failure, etc., but these are extra features (very standard in a real job scheduler) that I don't actually need.

I've found good ssh libraries for Python, things like classh and PuSSH, which don't have the (very simple) load balancing features I'd like.  On the other side of what I want is Condor or Slurm, as suggested by crispamares before I clarified I want something lighter.  Those would be doing things the proper way, but from reading about them, they sounds like spinning them up in user space only when I need them would be annoying to impossible.  This isn't a dedicated cluster, and I don't have root access on these hosts.

I'm currently planning to use a wrapper around classh with some basic polling of computers whenever I need to know how busy they are if I can't find something else.

答: You could modify buildbot and twisted? This seems like a good way to go.</p>

Title: Python library for job scheduling, ssh

Body:
I'd like to find a user-space tool (preferably in Python - barring that, in anything I could easily modify if it doesn't already do what I need it to) to replace a short script I've been using that does the two things below:

polls less than 100 computers (Fedora 13, it so happens) for load, available memory, and if it looks like someone is using them

selects good hosts for jobs, runs these jobs over ssh.  These jobs are the execution of arbitrary command line programs which read and write to a shared filesystem - typically image processing scripts or similar - cpu, sometimes memory intensive tasks.

For example, using my current script, I can in a python prompt

>>> import hosts
>>> hosts.run_commands(['users']*5)

or from the command line

% hosts.py "users" "users" "users" "users" "users"

to run the command users 5 times (after finding 5 computers on which the command could be run by checking the cpu load and available memory on at least 5 computers from a config file).  There should be no job server other than the script I just ran, and no worker daemons or processes on the computers that will run these commands.

I'd additionally like to be able to track the jobs, run jobs again on failure, etc., but these are extra features (very standard in a real job scheduler) that I don't actually need.

I've found good ssh libraries for Python, things like classh and PuSSH, which don't have the (very simple) load balancing features I'd like.  On the other side of what I want is Condor or Slurm, as suggested by crispamares before I clarified I want something lighter.  Those would be doing things the proper way, but from reading about them, they sounds like spinning them up in user space only when I need them would be annoying to impossible.  This isn't a dedicated cluster, and I don't have root access on these hosts.

I'm currently planning to use a wrapper around classh with some basic polling of computers whenever I need to know how busy they are if I can't find something else.


问:
How can I align the frequency bins with the fourier transform magnitude?
I am attempting to implement a Fast Fourier Transform with associated complex magnitude function on the STM32F411RE Nucleo developer board. My goal is to separate a combined signal with multiple sinusoidal elements into their separate frequency components, with correct amplitude.

My issues is that I cannot correctly line up the frequency bins outcomes from the Complex magnitude function with the frequencies. I am also starting to question the validity of these outcomes as such.

I have tried to use a number of different implementations posted by people for the FFT algorithm with the magnitude fix, most notably the examples listed on StackoverFlow by SleuthEye and Blog by LB9MG.

AFAIK I have a similar approach, but somehow their approaches yield the desired results and mine do not. Below is my code that I have altered to work via the implementation that SleuthEye has created.

```<code>int main(void)
{
    fftLen = 32;    // can be 32, 64, 128, 256, 512, 1024, 2048, 4096
    half_fftLen = fftLen/2;
    volatile float32_t sampleFreq = 50 * fftLen;    // Fs = binsize * fft length, desired binsize = 50 hz

    arm_rfft_fast_instance_f32 inst;
    arm_status status;
    status = arm_rfft_fast_init_f32(&inst, fftLen);

    float32_t signalCombined[fftLen] = {0};
    float32_t fftCombined[fftLen] = {0};
    float32_t fftMagnitude[fftLen] = {0};
    volatile float32_t fftFreq[fftLen] = {0};

    float32_t maxAmp;
    uint32_t maxAmpInd;

    while (1)
    {
        for (int i = 0; i< fftLen; i++)
        {
            signalCombined[i] = 40 * arm_sin_f32(450 * i); // 450 frequency at 40 amplitude
        }

        arm_rfft_fast_f32(&inst, signalCombined, fftCombined, 0); // perhaps switch to complex transform to allow for negative frequencies?
        arm_cmplx_mag_f32(fftCombined, fftMagnitude, half_fftLen);
        fftMagnitude[0] = fftCombined[0];
        fftMagnitude[half_fftLen] = fftCombined[1];

        arm_max_f32(fftMagnitude, half_fftLen, &maxAmp, &maxAmpInd); // We need the 3 max values

        for (int k = 0; k < fftLen ; k++)
        {
            fftFreq[k] = ((k*sampleFreq)/fftLen);
        }
}
</code>```

Shown below are the results that I get out of the code listed above: whilst I do get a magnitude out of the algorithms (at the correct index 12), it does not correspond to the  frequency or the amplitude of the input array signalCombined[].

Does anyone have an idea of why this is happening? Like so many of my errors it is probably a really trivial and stupid thing, but I cannot figure out for the life of me why this is happening.

EDIT: thanks to SleuthEye's help finding the frequencies is now possible, as the initial approach for generating the sin() signal was done incorrectly.

Some new issues popped up as the FFT only appears to yield the correct frequencies for the 32 samples, despite the bin size scaling accordingly to accommodate the adjusted sample size.

I am also unable to implement the amplitude fixing algorith: as per SleuthEye's Link with the example code 2*(1/N)*abs(X(k))^2 I have made my own implementation 2 * powf(fabs(fftMagnitude[j]), 2) / fftLen as shown in the code below, but this does not yield results that are even close to correct.

```<code>while (1)
{

    for (int i = 0; i < fftLen; i++)
    {
        signalCombined[i] =     400 * arm_sin_f32(2 * PI * 450 * i / sampleFreq);       // Sin Alpha, 400 amp at 10 kHz
//                      700 * arm_sin_f32(2 * PI * 33000 * i / sampleFreq) +        // Sin Bravo, 700 amp at 33 kHz
//                          300 * arm_sin_f32(2 * PI * 50000 * i / sampleFreq);             // Sin Charlie, 300 amp at 50 kHz
    }

    arm_rfft_fast_f32(&inst, signalCombined, fftCombined, 0); // calculate the fourier transform of the time domain signal
    arm_cmplx_mag_f32(fftCombined, fftMagnitude, half_fftLen);  // calculate the magnitude of the fourier transform
    fftMagnitude[0] = fftCombined[0];
    fftMagnitude[half_fftLen] = fftCombined[1];

    for (int j = 0; j < sizeof(fftMagnitude); j++)
    {
        fftMagnitude[j] = 2 * powf(fabs(fftMagnitude[j]), 2) / fftLen; // Algorithm to fix the amplitude of each unique frequency
    }

    arm_max_f32(fftMagnitude, half_fftLen, &maxAmp, &maxAmpInd); // We need the 3 max values

    for (int k = 0; k < fftLen ; k++)
    {
        fftFreq[k] = ((k*sampleFreq)/fftLen);
    }
}
</code>```

答:
Your tone generation does not take into account the sampling frequency of 1600Hz, so you are effectively generating a tone at a frequency of 450*1600/(2*PI) ~ 114591Hz which gets aliased to ~608Hz. That 608Hz frequency roughly corresponds to a frequency index around 12 when using an FFT size of 32.

The generation of a 450Hz tone at a 1600Hz sampling frequency should be done as follows:

```<code>for (int i = 0; i< fftLen; i++)
{
    signalCombined[i] = 40 * arm_sin_f32(2 * PI * 450 * i / sampleFreq);
}
</code>```

As far as matching the amplitude, keep in kind that there is a scaling factor between the time-domain and frequency-domain of approximately 0.5*fftLen (see this other post of mine).

Body:
I am attempting to implement a Fast Fourier Transform with associated complex magnitude function on the STM32F411RE Nucleo developer board. My goal is to separate a combined signal with multiple sinusoidal elements into their separate frequency components, with correct amplitude.

My issues is that I cannot correctly line up the frequency bins outcomes from the Complex magnitude function with the frequencies. I am also starting to question the validity of these outcomes as such.

I have tried to use a number of different implementations posted by people for the FFT algorithm with the magnitude fix, most notably the examples listed on StackoverFlow by SleuthEye and Blog by LB9MG.

AFAIK I have a similar approach, but somehow their approaches yield the desired results and mine do not. Below is my code that I have altered to work via the implementation that SleuthEye has created.

int main(void)
{
    fftLen = 32;    // can be 32, 64, 128, 256, 512, 1024, 2048, 4096
    half_fftLen = fftLen/2;
    volatile float32_t sampleFreq = 50 * fftLen;    // Fs = binsize * fft length, desired binsize = 50 hz

    arm_rfft_fast_instance_f32 inst;
    arm_status status;
    status = arm_rfft_fast_init_f32(&inst, fftLen);

    float32_t signalCombined[fftLen] = {0};
    float32_t fftCombined[fftLen] = {0};
    float32_t fftMagnitude[fftLen] = {0};
    volatile float32_t fftFreq[fftLen] = {0};

    float32_t maxAmp;
    uint32_t maxAmpInd;

    while (1)
    {
        for (int i = 0; i< fftLen; i++)
        {
            signalCombined[i] = 40 * arm_sin_f32(450 * i); // 450 frequency at 40 amplitude
        }

        arm_rfft_fast_f32(&inst, signalCombined, fftCombined, 0); // perhaps switch to complex transform to allow for negative frequencies?
        arm_cmplx_mag_f32(fftCombined, fftMagnitude, half_fftLen);
        fftMagnitude[0] = fftCombined[0];
        fftMagnitude[half_fftLen] = fftCombined[1];

        arm_max_f32(fftMagnitude, half_fftLen, &maxAmp, &maxAmpInd); // We need the 3 max values

        for (int k = 0; k < fftLen ; k++)
        {
            fftFreq[k] = ((k*sampleFreq)/fftLen);
        }
}

Shown below are the results that I get out of the code listed above: whilst I do get a magnitude out of the algorithms (at the correct index 12), it does not correspond to the  frequency or the amplitude of the input array signalCombined[].

Does anyone have an idea of why this is happening? Like so many of my errors it is probably a really trivial and stupid thing, but I cannot figure out for the life of me why this is happening.

EDIT: thanks to SleuthEye's help finding the frequencies is now possible, as the initial approach for generating the sin() signal was done incorrectly.

Some new issues popped up as the FFT only appears to yield the correct frequencies for the 32 samples, despite the bin size scaling accordingly to accommodate the adjusted sample size.

I am also unable to implement the amplitude fixing algorith: as per SleuthEye's Link with the example code 2*(1/N)*abs(X(k))^2 I have made my own implementation 2 * powf(fabs(fftMagnitude[j]), 2) / fftLen as shown in the code below, but this does not yield results that are even close to correct.

while (1)
{

    for (int i = 0; i < fftLen; i++)
    {
        signalCombined[i] =     400 * arm_sin_f32(2 * PI * 450 * i / sampleFreq);       // Sin Alpha, 400 amp at 10 kHz
//                      700 * arm_sin_f32(2 * PI * 33000 * i / sampleFreq) +        // Sin Bravo, 700 amp at 33 kHz
//                          300 * arm_sin_f32(2 * PI * 50000 * i / sampleFreq);             // Sin Charlie, 300 amp at 50 kHz
    }

    arm_rfft_fast_f32(&inst, signalCombined, fftCombined, 0); // calculate the fourier transform of the time domain signal
    arm_cmplx_mag_f32(fftCombined, fftMagnitude, half_fftLen);  // calculate the magnitude of the fourier transform
    fftMagnitude[0] = fftCombined[0];
    fftMagnitude[half_fftLen] = fftCombined[1];

    for (int j = 0; j < sizeof(fftMagnitude); j++)
    {
        fftMagnitude[j] = 2 * powf(fabs(fftMagnitude[j]), 2) / fftLen; // Algorithm to fix the amplitude of each unique frequency
    }

    arm_max_f32(fftMagnitude, half_fftLen, &maxAmp, &maxAmpInd); // We need the 3 max values

    for (int k = 0; k < fftLen ; k++)
    {
        fftFreq[k] = ((k*sampleFreq)/fftLen);
    }
}

Body:
Your tone generation does not take into account the sampling frequency of 1600Hz, so you are effectively generating a tone at a frequency of 450*1600/(2*PI) ~ 114591Hz which gets aliased to ~608Hz. That 608Hz frequency roughly corresponds to a frequency index around 12 when using an FFT size of 32.

The generation of a 450Hz tone at a 1600Hz sampling frequency should be done as follows:

for (int i = 0; i< fftLen; i++)
{
    signalCombined[i] = 40 * arm_sin_f32(2 * PI * 450 * i / sampleFreq);
}

As far as matching the amplitude, keep in kind that there is a scaling factor between the time-domain and frequency-domain of approximately 0.5*fftLen (see this other post of mine).


问:
shouldn't unreachable code after os.Exit be flagged
go 1.12 window

misplaced a fmt.Println after os.Exit instead of before,
shouldn't this have gotten a compiler failure or at least warning?

```<code>package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Println("Hello, playground")
    os.Exit(0)
    fmt.Println("Good By, playground")
}
</code>```

答:
os.Exit() is just like any other function, the compiler should not know it terminates the app and so the rest of the code that follows is unreachable. os.Exit() is just one example and there are more, e.g.log.Fatal() (which calls os.Exit()). Not to mention you can also create a function which calls one of these, how far should the compiler go to detect all or most of these?

Going further, the Go compiler does not detect nor marks "truly" unreachable code. The following variation when using a return statement could even be obvious to the compiler:

```<code>func main() {
    fmt.Println("Hello, playground")
    return
    fmt.Println("Good By, playground")
}
</code>```

Yet it compiles and runs just fine, and outputs (try it on the Go Playground):

```<code>Hello, playground
</code>```

So the compiler does not detect unreachable code, but go vet does, which is also run by the Go Playground, and so you can see the app's output prefixed by:

```<code>./prog.go:10:2: unreachable code
Go vet exited.
</code>```

This has been brought up before, see cmd/gc: report unreachable code #9501. Robert Grisemer's response was:

Generally, Go's philosophy is not to protect the programmer at all costs from his/her mistakes. It's deliberate to not raise an error for unreachable code. It's also not a very common kind of mistake. Besides, it's often useful to introduce early returns for debugging which may cause plenty of unreachable code. It's not clear the benefits outweigh the costs and disadvantages.

Unused variables can lead to subtle find bugs in conjunction with Go's re-declaration mechanism in short variable declarations - hence the error message for unused variables. This is a mechanism that evolved from experience and is a pragmatic solution for a concrete problem.

Unused imports are reported because it helps keeping dependencies under control - an important tool in large-scale systems design and as a side-effect it also keeps compile times fast. Again a very deliberate design decision.

Finally, making dead code an error would be a significant language change which is out of the question at this point.

Use go vet.

Body:
go 1.12 window

misplaced a fmt.Println after os.Exit instead of before,
shouldn't this have gotten a compiler failure or at least warning?

package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Println("Hello, playground")
    os.Exit(0)
    fmt.Println("Good By, playground")
}

Body:
os.Exit() is just like any other function, the compiler should not know it terminates the app and so the rest of the code that follows is unreachable. os.Exit() is just one example and there are more, e.g.log.Fatal() (which calls os.Exit()). Not to mention you can also create a function which calls one of these, how far should the compiler go to detect all or most of these?

Going further, the Go compiler does not detect nor marks "truly" unreachable code. The following variation when using a return statement could even be obvious to the compiler:

func main() {
    fmt.Println("Hello, playground")
    return
    fmt.Println("Good By, playground")
}

Yet it compiles and runs just fine, and outputs (try it on the Go Playground):

Hello, playground

So the compiler does not detect unreachable code, but go vet does, which is also run by the Go Playground, and so you can see the app's output prefixed by:

./prog.go:10:2: unreachable code
Go vet exited.

This has been brought up before, see cmd/gc: report unreachable code #9501. Robert Grisemer's response was:

Generally, Go's philosophy is not to protect the programmer at all costs from his/her mistakes. It's deliberate to not raise an error for unreachable code. It's also not a very common kind of mistake. Besides, it's often useful to introduce early returns for debugging which may cause plenty of unreachable code. It's not clear the benefits outweigh the costs and disadvantages.

Unused variables can lead to subtle find bugs in conjunction with Go's re-declaration mechanism in short variable declarations - hence the error message for unused variables. This is a mechanism that evolved from experience and is a pragmatic solution for a concrete problem.

Unused imports are reported because it helps keeping dependencies under control - an important tool in large-scale systems design and as a side-effect it also keeps compile times fast. Again a very deliberate design decision.

Finally, making dead code an error would be a significant language change which is out of the question at this point.

Use go vet.


问:
Primefaces p:poll breaks 'rendered' functionality
I have a dropdown with ajax event to hide/show another component based on 'rendered' attribute.

It works fine, untill p:poll from another component gets invoked - the ajax event does not toggle the 'airportPickupWrapper' (although i can see the ajax request in Network)

component 1 :

```<code><h:outputLink id="unresolvedOrdersCount" value="#{navigationMenuBean.setPage('management/orderManagement')}" style="color : red">
            New orders : #{headerController.getUnresolvedOrdersCount()}
</h:outputLink>

<p:poll interval="10" update="unresolvedOrdersCount"/>
</code>```

component2 :

```<code><h:selectOneMenu id="orderTypeDropdown" value="#{orderController.order.orderType}">
    <f:selectItems value="#{orderController.orderTypes}"
                   var="orderType"
                   itemLabel="#{orderType.displayName}">
    </f:selectItems>
    <p:ajax event="change" update="airportPickupWrapper"/>
</h:selectOneMenu>
<p:panel id="airportPickupWrapper" >
    <h:panelGrid columns="1" rendered="#{orderController.order.orderType.name() == 'AIRPORT_PICKUP'}">
        <p:outputLabel for="flightNumber" value="Flight number: " />
        <p:inputText id="flightNumber" value="#{orderController.order.flightNumber}">

        </p:inputText>
    </h:panelGrid>
</p:panel>
</code>```

thank you for suggestions

edit: if i change the component 1 so that it does not invoke backing bean, everything works fine

```<code><h:outputLink id="unresolvedOrdersCount"></h:outputLink>
</code>```

答:
Solved.

The problem was i used h:outputLink, where xmlns:h="http://xmlns.jcp.org/jsf/html".
I switched it to p:link (xmlns:p="http://primefaces.org/ui") and everything works fine.

One would think it is compatible.

Thank you.

Body:
I have a dropdown with ajax event to hide/show another component based on 'rendered' attribute.

It works fine, untill p:poll from another component gets invoked - the ajax event does not toggle the 'airportPickupWrapper' (although i can see the ajax request in Network)

component 1 :

<h:outputLink id="unresolvedOrdersCount" value="#{navigationMenuBean.setPage('management/orderManagement')}" style="color : red">
            New orders : #{headerController.getUnresolvedOrdersCount()}
</h:outputLink>

component2 :

<h:selectOneMenu id="orderTypeDropdown" value="#{orderController.order.orderType}">
    <f:selectItems value="#{orderController.orderTypes}"
                   var="orderType"
                   itemLabel="#{orderType.displayName}">
    </f:selectItems>

</h:selectOneMenu>

    <h:panelGrid columns="1" rendered="#{orderController.order.orderType.name() == 'AIRPORT_PICKUP'}">

    </h:panelGrid>

thank you for suggestions

edit: if i change the component 1 so that it does not invoke backing bean, everything works fine

<h:outputLink id="unresolvedOrdersCount"></h:outputLink>


问:
Can't figure out the correct way to implement if statement on dataframe with apply lambda
Say I have a simple dataframe (df) with two columns (Name and Value). I want to add a third column (New Value) based on Name.

I have tried:

```<code>df['New Value'] = df[['Name ']].apply((lambda x: df['Value'] * 2 if x == 'John' else df['Value']) , axis=0)
</code>```

By doing this I get the following error:

ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index Name')

What I understand is that x is a Series and I cannot compare to a string, is this correct? If not, what does it mean?

In any case, how do I go around this problem?

答:
You are applying the operation on a dataframe of column only 'Name' and when working with row wise operation, set axis=1

Try this for your usecase.

df['New Value'] = df.apply(lambda x: x['Value'] * 2 if x['Name'] == 'John' else x['Value'], axis=1)
```

<p>Solution</p>

<pre class="lang-py prettyprint-override"><code>In [49]: df
Out[49]:
    Name  Value
0   John      5
1  Kevin      5

In [50]: df['New Value'] = df.apply(lambda x: x['Value'] * 2 if x['Name'] == 'John' else x['Value'], axis=1)

In [51]: df
Out[51]:
    Name  Value  New Value
0   John      5         10
1  Kevin      5          5
</code>```

Body:
Say I have a simple dataframe (df) with two columns (Name and Value). I want to add a third column (New Value) based on Name.

I have tried:

df['New Value'] = df[['Name ']].apply((lambda x: df['Value'] * 2 if x == 'John' else df['Value']) , axis=0)

By doing this I get the following error:

ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index Name')

What I understand is that x is a Series and I cannot compare to a string, is this correct? If not, what does it mean?

In any case, how do I go around this problem?

Body:
You are applying the operation on a dataframe of column only 'Name' and when working with row wise operation, set axis=1

Try this for your usecase.

df['New Value'] = df.apply(lambda x: x['Value'] * 2 if x['Name'] == 'John' else x['Value'], axis=1)

Solution

In [49]: df
Out[49]:
    Name  Value
0   John      5
1  Kevin      5

In [50]: df['New Value'] = df.apply(lambda x: x['Value'] * 2 if x['Name'] == 'John' else x['Value'], axis=1)

In [51]: df
Out[51]:
    Name  Value  New Value
0   John      5         10
1  Kevin      5          5


问:
A safe way to get some deep value
Suppose I have a fairly deep class, and I need to get some field embedded deep within

```<code>int? result = this.child.button.data;
return result;
</code>```

And at any point, it could be pointing to a null, in which case I want to return null as well. A common approach would be

```<code>if (this.child != null && this.child.button!= null) {
  return this.child.button.data;
} else {
  return null;
}
</code>```

But if the field is REALLY deep nested, then the only solution I can think of is this:

```<code>int? result = null;
try {
  result = this.child.button.handler.controller.renderer.data;
} catch (NullReferenceException ex) {
  // Do nothing here
}
</code>```

Is this the correct approach, or is there a better solution?

答:
you may check the null conditional operator in C# - ?.
Like:</p>

```<code>result = this?.child?.button?.handler?.controller?.renderer?.data;
</code>```

Title: A safe way to get some deep value

Body:
Suppose I have a fairly deep class, and I need to get some field embedded deep within

int? result = this.child.button.data;
return result;

And at any point, it could be pointing to a null, in which case I want to return null as well. A common approach would be

if (this.child != null && this.child.button!= null) {
  return this.child.button.data;
} else {
  return null;
}

But if the field is REALLY deep nested, then the only solution I can think of is this:

int? result = null;
try {
  result = this.child.button.handler.controller.renderer.data;
} catch (NullReferenceException ex) {
  // Do nothing here
}

Is this the correct approach, or is there a better solution?

Body:
you may check the null conditional operator in C# - ?.
Like:

result = this?.child?.button?.handler?.controller?.renderer?.data;


问:
Where is NSAlert.h in the iOS  SDK?
According to iOS's Using and Creating Error Objects, one can display a error object with the following code.

```<code>NSError *theError = nil;
BOOL success = [myDoc writeToURL:[self docURL] ofType:@"html" error:&theError];

if (success == NO) {
    // Maybe try to determine cause of error and recover first.
    NSAlert *theAlert = [NSAlert alertWithError:theError];
    [theAlert runModal]; // Ignore return value.
}
</code>```

Unfortunately, I am not smart enough to figure out how to include NSAlert.h.

Any help would be appreciated.

答:
That document is referring to the (OS X) AppKit framework.  Right after that box, it says:

(UIAlertView, the UIKit class corresponding to NSAlert, has no equivalent method for alertWithError:.)

You can still use UIAlertView, but you'll need to manually populate the title, message, and button strings from the error.

Title: Where is NSAlert.h in the iOS  SDK?

Body:
According to iOS's Using and Creating Error Objects, one can display a error object with the following code.

NSError *theError = nil;
BOOL success = [myDoc writeToURL:[self docURL] ofType:@"html" error:&theError];

if (success == NO) {
    // Maybe try to determine cause of error and recover first.
    NSAlert *theAlert = [NSAlert alertWithError:theError];
    [theAlert runModal]; // Ignore return value.
}

Unfortunately, I am not smart enough to figure out how to include NSAlert.h.

Any help would be appreciated.


问:
Store and compare android sensor(accelerometer) data sets to match the pattern
I am developing android application which will learn and than evaluate aggressive driving behavior i.e. sharp turns, sudden brake etc...

As i am trying to make a learning algorithm. My approach now is to get sensor data when wrongly driven and make data sets of multiple sensors i.e. Accelerometer, Gyroscope and magnetometer.

Once multiple datasets(for each sensor) stored, the application will keep on comparing the datasets with the current values of the sensors. If pattern matched, same action(wrong) occurred.

Is there any api or solution to how can i compare and match the pattern of the sensor data, as currently i am using arrays and am comparing the multiple values which wont work, i know.

Or is there another solution to the problem which you think is better kindly lemme know.

It would be a great help as i am stuck here from weeks :(

答:
This seem to be nlp problem where we need to find the patterns between the two data.You can make use of latent semantic analysis.There is one library gensim which is completely free to use.
If the purpose is not solved by nlp approach then go for clustering. The clustering algorithm. Or if you have data only for one class (say when the diver is driving wrong)  then use baysian approach.For one class it will work better.


问:
Scraping code found when viewing page source
I'm trying to scrape code from a website that is found when right-clicking and selecting "view page source." My code below scrapes from the output found when you right click then select "inspect" I think. I get an error that says "file was loaded in the wrong encoding: 'UTF-8' I'm data mining based upon the raw page source info and I don't know how to pull that in.

See below

```<code>from bs4 import BeautifulSoup
import requests
import urllib.request
import urllib.error
import os, os.path, csv
import sys
from lxml import html
import requests

sys.stdout = open('scrapingoutput', 'a')
print(sys.stdout)

url= "https://www.geodatadirect.com/SearchResults/SuffolkSearchResults.aspx?state=NY&id=Suffolk&type=Sales"

urllib.request.urlopen("https://www.geodatadirect.com/SearchResults/SuffolkSearchResults.aspx?state=NY&id=Suffolk&type=Sales").read()

content = urllib.request.urlopen(url).read()

soup = BeautifulSoup(content)

print(soup.prettify())
</code>```

答:
```<code>import requests
import bs4
url = "https://www.geodatadirect.com/SearchResults/SuffolkSearchResults.aspx?state=NY&id=Suffolk&type=Sales"

page_content = requests.get(url).content
soup = bs4.BeautifulSoup(page_content, 'html.parser')
print(soup.prettify())
</code>```

this prints

```<code><!DOCTYPE html>
<html>
 <head>
  <title>
   Nationwide Property Data, Reports, Sales Comps
  </title>
  <meta charset="utf-8"/>
...
</code>```

Body:
I'm trying to scrape code from a website that is found when right-clicking and selecting "view page source." My code below scrapes from the output found when you right click then select "inspect" I think. I get an error that says "file was loaded in the wrong encoding: 'UTF-8' I'm data mining based upon the raw page source info and I don't know how to pull that in.

See below

from bs4 import BeautifulSoup
import requests
import urllib.request
import urllib.error
import os, os.path, csv
import sys
from lxml import html
import requests

sys.stdout = open('scrapingoutput', 'a')
print(sys.stdout)

url= "https://www.geodatadirect.com/SearchResults/SuffolkSearchResults.aspx?state=NY&id=Suffolk&type=Sales"

urllib.request.urlopen("https://www.geodatadirect.com/SearchResults/SuffolkSearchResults.aspx?state=NY&id=Suffolk&type=Sales").read()

content = urllib.request.urlopen(url).read()

soup = BeautifulSoup(content)

print(soup.prettify())

Body:
import requests
import bs4
url = "https://www.geodatadirect.com/SearchResults/SuffolkSearchResults.aspx?state=NY&id=Suffolk&type=Sales"

page_content = requests.get(url).content
soup = bs4.BeautifulSoup(page_content, 'html.parser')
print(soup.prettify())

this prints

<!DOCTYPE html>
<html>
 <head>
  <title>
   Nationwide Property Data, Reports, Sales Comps
  </title>
  <meta charset="utf-8"/>
...


问:
Equivalent of template context in Pyramid (pylons user)
What is the equivalent of template context in Pyramid?

Does the IBeforeRender event in pyramid have anything to with this? I've gone through the official documentation but diffcult to understand what the IBeforeRender event is exactly.

答:
Pyramid doesn't really expose the "template context" to the developer (although it is used internally in the various template engine bindings for Pyramid).

Normally if you want to stuff something into "c" for use inside a template you simply pass it as a keyword argument to the render_to_response() call or as part of the dict that you return with a predefined renderer.

So to do something similar as http://pylonsbook.com/en/1.1/using-view-templates.html#using-the-template-context-c-global you would do:

```<code>@view_config(renderer="greeting.mako")
def index(request):
    return {'name': 'Pyramid Developer'}
</code>```

And greeting.mako :

```<code><html>
<head>
    <title>Greetings</title>
</head>
<body>
    <h1>Greetings</h1>
    <p>Hello ${name}!</p>
</body>
</html>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Pyramid doesn't really expose the "template context" to the developer (although it is used internally in the various template engine bindings for Pyramid).

Normally if you want to stuff something into "c" for use inside a template you simply pass it as a keyword argument to the render_to_response() call or as part of the dict that you return with a predefined renderer.

So to do something similar as http://pylonsbook.com/en/1.1/using-view-templates.html#using-the-template-context-c-global you would do:

@view_config(renderer="greeting.mako")
def index(request):
    return {'name': 'Pyramid Developer'}

And greeting.mako :

<html>
<head>
    <title>Greetings</title>
</head>
<body>
    <h1>Greetings</h1>
    <p>Hello ${name}!</p>
</body>
</html>


问:
How to generate fingerprint for group chat or MUC using SMACK OMEMO?
I am making a chat app for android. Where i have use SMACK library and also I have use omemo for message encryption. I can generate, encrypt and send - receive message to other user. But I am unable to generate fingerprint for MUC means group chat. </p>

答:
You don't have to "generate fingerprint" for MUC usage. OMEMO uses the same identity keys for MUC as are used in one-to-one chats. Basically a message to a group chat is simply encrypted for each and every recipient.

Sorry code sample is not possible because of secrecy. But i can give some hints.

You are aware of the fact that smack-omemo-signal is licensed under GPLv3, right? ;)


问:
Invisible character leads to Unexpected EOF error
While trying to handle a string I am facing

Error: SyntaxError: Unexpected EOF

I have no control on how the string is generated.  I managed to isolate the problematic character(s) by dichotomy with substring(), however it doesn't get printed either by console.log() or by JSON.parse() : I get

```<code>> console.log(c);
""
> JSON.parse(c);
""
</code>```

yet

```<code>> c.length;
1
</code>```

All I know is that it is followed by a \n.

How can I identify it and get rid of it ?

Update

```<code>> console.log(encodeURIComponent(c));
%E2%80%A8
</code>```

Is this even a character ??

答:
Assuming this is the only problematic character, and since its percent-encoding has been identified, a solution is to replace the decoded percent-encoding string :

```<code>> c.length;
1
> let badchar = decodeURI("%E2%80%A8");
> let regex = new RegExp(badchar, "g");
> newc = c.replace(regex, "");
> newc.length;
0
</code>```

Or if for some reason RegExp is not available :

```<code>> newc = c.split(badchar).join("")
</code>```

Body:
While trying to handle a string I am facing

Error: SyntaxError: Unexpected EOF

I have no control on how the string is generated.  I managed to isolate the problematic character(s) by dichotomy with substring(), however it doesn't get printed either by console.log() or by JSON.parse() : I get

> console.log(c);
""
> JSON.parse(c);
""

yet

> c.length;
1

All I know is that it is followed by a \n.

How can I identify it and get rid of it ?

Update

> console.log(encodeURIComponent(c));
%E2%80%A8

Is this even a character ??

Body:
Assuming this is the only problematic character, and since its percent-encoding has been identified, a solution is to replace the decoded percent-encoding string :

> c.length;
1
> let badchar = decodeURI("%E2%80%A8");
> let regex = new RegExp(badchar, "g");
> newc = c.replace(regex, "");
> newc.length;
0

Or if for some reason RegExp is not available :

> newc = c.split(badchar).join("")


问:
DocuSign API - Specify redirect URL after email signing ceremony is completed
I am creating an envelope that should be signed by a Signer using the email flow.

I would like the Signer to be redirected to a specific URL after they complete the signing session. How can I achieve this?

For the RecipientViewRequest (ie. for an embedded signing session), there is a ReturnURL that I can specify. I can't find a similar property to specify for the email flow.

答:
Post-signing landing pages aren't directly configurable through the API.

That said, those can be configured through your account's Branding: https://docs.docusign.com/supportdocs/ndse-admin-guide/Content/advanced-branding-configuration.htm#URLs

By setting Go to Admin > Brand (Or Brands: Edit) > Destination URLs, you can direct email signers to pages you control. If your account has multiple brands enabled, you can create multiple configurations and apply them to envelopes using the brandId parameter.

If you don't have Branding enabled on your account, you'll want to reach out to your Account Manager, or to the Sales team to discuss.


问:
Position div depending on the height of another div
I have a
 (let's call it "image") that contains some images  and so on.
This div's width is set at 100% of the screen, and the images inside rescale depending on the width. So, depending on the browser's width, the height of my div changes.

Now I would like to create another div (let's call it "after_image") that starts after this image, without using "relative", but by retrieving the height of
, and using that as a "top: px" attribute.

Is it possible? Maybe a

答:
Try this :

```

Body:
Try this :

<div id='image'>
  <img src='' />
  <img src='' />
  <img src='' />
</div>
<div id='after_image'></div>

<script>
  var h = document.getElementById('image').clientHeight // returns height as number
  document.getElementById('after_image').style.top = h + 'px'
</script>


问:
Getting "The path to the driver executable must be set by the webdriver.chrome.driver system property"though set correct path
My code is very simple
code:

```<code>WebDriver wd =new ChromeDriver();
  System.setProperty("webdriver.chrome.driver",
                     "D:\\List_of_Jar\\chromedriver.exe");
       String baseUrl = "https://www.google.com";wd.get(baseUrl);
</code>```

have downloaded and added jar as "Java-3.4.0" from selenium hq site.
Download Google Chrome Driver-2.29 from the same website and located it in "D:\List_of_Jar" path.

When I run the above code I getting an error as

```<code>java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://chromedriver.storage.googleapis.com/index.html
at com.google.common.base.Preconditions.checkState(Preconditions.java:738)
</code>```

Getting version error though did proper configuration. so kindly help me for fixing the issue.

Details:

OS: Windows XP.

Java : JDK1.8 and JRE1.8.

Selenium : version 3.4

答:
You should use Chocolatey as the Selenium wiki dictates.  It will work straight away.

Windows users with Chocolatey installed: choco install chromedriver

https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver

Body:
My code is very simple
code:

WebDriver wd =new ChromeDriver();
  System.setProperty("webdriver.chrome.driver",
                     "D:\\List_of_Jar\\chromedriver.exe");
       String baseUrl = "https://www.google.com";wd.get(baseUrl);

have downloaded and added jar as "Java-3.4.0" from selenium hq site.
Download Google Chrome Driver-2.29 from the same website and located it in "D:\List_of_Jar" path.

When I run the above code I getting an error as

java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://chromedriver.storage.googleapis.com/index.html
at com.google.common.base.Preconditions.checkState(Preconditions.java:738)

Getting version error though did proper configuration. so kindly help me for fixing the issue.

Details:

OS: Windows XP.

Java : JDK1.8 and JRE1.8.

Selenium : version 3.4


问:
How to utilize Heroku's 'postdeploy' script to create table within a provisioned Heroku PostgreSQL database?
I am working on a web app that is set up on Heroku. I'd like others to be able to use it themselves, so I'm trying to create a 'Deploy to Heroku' button to include in my repository's README.

Following along with Heroku's documentation1,2, I created an app.json file which outlines everything Heroku needs to provision the app. Here is what my app.json file looks like:

```<code>{
  "name": "[title]",
  "author": "[author]",
  "description": "[desc]",
  "repository": "[https://github.com/[user]/[repo]",
  "logo": "[url]",
  "addons": [
    "heroku-postgresql:hobby-dev",
    "wwwhisper:solo"
  ],
  "scripts": {
    "postdeploy": "node server/models/database.js"
  },
  "env": {
    "TZ": "America/Los_Angeles"
  }
}
</code>```

As you can see, the postdeploy script is supposed to call the database.js script, which looks like so:

```<code>const pg = require('pg');
const connectionString = process.env.DATABASE_URL;

const client = new pg.Client(connectionString);

client.connect();
client.query('CREATE TABLE IF NOT EXISTS table_name (id uuid, url VARCHAR(2000), \
  title TEXT, description TEXT, been_visited BOOLEAN DEFAULT false, created_at TIMESTAMP DEFAULT NOW())', (err, res) => {
    if (err) {
      client.end();
      return console.error('error with PostgreSQL database', err);
    }
});

client.end();
</code>```

I know the query works as I tested it locally, but when I test the button with the above app.json, I still get the error error: relation "tanabata_tree" does not exist - meaning the table was never created.

Where / what am I doing wrong?

1: https://devcenter.heroku.com/articles/heroku-button
https://devcenter.heroku.com/articles/heroku-button

2: https://devcenter.heroku.com/articles/app-json-schema

答:
You have your client.end(); outside your database query callback function. Your database connection is ended before your create table query is finished because JavaScript is Asynchronous.

The solution is to put your client.end(); inside your callback function so it gets called after your database query finishes.

Here is the working code:

```<code>const connectionString = process.env.DATABASE_URL;

const client = new pg.Client(connectionString);

client.connect();
client.query('CREATE TABLE IF NOT EXISTS table_name (id uuid, url VARCHAR(2000), \
  title TEXT, description TEXT, been_visited BOOLEAN DEFAULT false, created_at TIMESTAMP DEFAULT NOW())', (err, res) => {
    if (err) {
      return console.error('error with PostgreSQL database', err);
    }
    client.end();
});
</code>```

Body:
I am working on a web app that is set up on Heroku. I'd like others to be able to use it themselves, so I'm trying to create a 'Deploy to Heroku' button to include in my repository's README.

Following along with Heroku's documentation1,2, I created an app.json file which outlines everything Heroku needs to provision the app. Here is what my app.json file looks like:

{
  "name": "[title]",
  "author": "[author]",
  "description": "[desc]",
  "repository": "[https://github.com/[user]/[repo]",
  "logo": "[url]",
  "addons": [
    "heroku-postgresql:hobby-dev",
    "wwwhisper:solo"
  ],
  "scripts": {
    "postdeploy": "node server/models/database.js"
  },
  "env": {
    "TZ": "America/Los_Angeles"
  }
}

As you can see, the postdeploy script is supposed to call the database.js script, which looks like so:

const pg = require('pg');
const connectionString = process.env.DATABASE_URL;

const client = new pg.Client(connectionString);

client.connect();
client.query('CREATE TABLE IF NOT EXISTS table_name (id uuid, url VARCHAR(2000), \
  title TEXT, description TEXT, been_visited BOOLEAN DEFAULT false, created_at TIMESTAMP DEFAULT NOW())', (err, res) => {
    if (err) {
      client.end();
      return console.error('error with PostgreSQL database', err);
    }
});

client.end();

I know the query works as I tested it locally, but when I test the button with the above app.json, I still get the error error: relation "tanabata_tree" does not exist - meaning the table was never created.

Where / what am I doing wrong?

1: https://devcenter.heroku.com/articles/heroku-button
https://devcenter.heroku.com/articles/heroku-button

2: https://devcenter.heroku.com/articles/app-json-schema

Body:
You have your client.end(); outside your database query callback function. Your database connection is ended before your create table query is finished because JavaScript is Asynchronous.

The solution is to put your client.end(); inside your callback function so it gets called after your database query finishes.

Here is the working code:

const connectionString = process.env.DATABASE_URL;

const client = new pg.Client(connectionString);

client.connect();
client.query('CREATE TABLE IF NOT EXISTS table_name (id uuid, url VARCHAR(2000), \
  title TEXT, description TEXT, been_visited BOOLEAN DEFAULT false, created_at TIMESTAMP DEFAULT NOW())', (err, res) => {
    if (err) {
      return console.error('error with PostgreSQL database', err);
    }
    client.end();
});


问:
A middleware containing res.locals is not working
Hi I am using this given middleware to show username userid etc on every template but this middleware is not working neither console.log working nor locals working in my ejs template. Please check why!

I am using this middleware in the last before app.listen.

```<code>app.use(function(req, res, next) {
    console.log("Hello");
    res.locals.username = req.session.username;
    res.locals.userid = req.session.userid;
    res.locals.w_id = req.session.w_id;
      next();
  });
</code>```

答:
```<code>I am using this middleware in the last before app.listen.
</code>```

That's your issue, you must add this middleware before all the routes so that it will be called.

Body:
Hi I am using this given middleware to show username userid etc on every template but this middleware is not working neither console.log working nor locals working in my ejs template. Please check why!

I am using this middleware in the last before app.listen.

app.use(function(req, res, next) {
    console.log("Hello");
    res.locals.username = req.session.username;
    res.locals.userid = req.session.userid;
    res.locals.w_id = req.session.w_id;
      next();
  });

Body:
I am using this middleware in the last before app.listen.

That's your issue, you must add this middleware before all the routes so that it will be called.