问:
Rxjs error with pipe of operators
I have an error in switchMap operator:

```<code>@Injectable()
export class AvailableStoreTypesLoadedEffect {
constructor(private actions$: Actions,
          private service: AvailableService) {

}

 @Effect()
 AvailableStoreTypesLoadedEffect$ = this.actions$
 .ofType(FETCH_AVAILABLE_STORE_TYPES)
 .pipe(
   switchMap(action => this.service.fetchAvailableStoreTypes()),//Error:(22, 9) TS2684:The 'this' context of type 'void' is not assignable to method's 'this' of type 'Observable<{}>'.
   map(res => new AvailableStoreTypesLoaded(res))
  );
}
</code>```

I tried with:

```<code>Observable.of({})
  .pipe(
    switchMap(() => Observable.of({}))//Error:(22, 9) TS2684:The 'this' context of type 'void' is not assignable to method's 'this' of type 'Observable<{}>'.
  );
</code>```

but I get the same error.

My environment is:

angular 5.0.3

typescript 2.4.2

rxjs 5.5.2

答: I imported the library from import { mergeMap } from 'rxjs/operator/mergeMap'; but it must be imported from import { mergeMap } from 'rxjs/operators';

Title: Rxjs error with pipe of operators

Body:
I have an error in switchMap operator:

@Injectable()
export class AvailableStoreTypesLoadedEffect {
constructor(private actions$: Actions,
          private service: AvailableService) {

}

 @Effect()
 AvailableStoreTypesLoadedEffect$ = this.actions$
 .ofType(FETCH_AVAILABLE_STORE_TYPES)
 .pipe(
   switchMap(action => this.service.fetchAvailableStoreTypes()),//Error:(22, 9) TS2684:The 'this' context of type 'void' is not assignable to method's 'this' of type 'Observable<{}>'.
   map(res => new AvailableStoreTypesLoaded(res))
  );
}

I tried with:

Observable.of({})
  .pipe(
    switchMap(() => Observable.of({}))//Error:(22, 9) TS2684:The 'this' context of type 'void' is not assignable to method's 'this' of type 'Observable<{}>'.
  );

but I get the same error.

My environment is:

angular 5.0.3

typescript 2.4.2

rxjs 5.5.2


来源: stackexchange

问:
SFML Sprite not displaying
I recently started learning SFML and I am trying to display an image. The image is supposed to be displayed on the screen and be movable with arrow keys and WASD.

However, am getting a blank screen with an error Failed to load image "image.png". Reason: Unable to open file, when I display a bitmap it works. How can I fix this?

```<code>// ConsoleApplication8.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <SFML\Graphics.hpp>
#include <iostream>

int main()
{
    sf::RenderWindow window(sf::VideoMode::getDesktopMode(), "SFML works!", sf::Style::Resize | sf::Style::Default);
    sf::CircleShape shape(100.f);
    sf::Vector2i position(-9,0);
    shape.setFillColor(sf::Color::Green);
    sf::Texture texture;
    if (!texture.loadFromFile("image.png", sf::IntRect(10, 10, 32, 32)))
    {
        std::cout << "Could not load image\n";
        system("pause");

    }
    sf::Sprite Sprite;
    Sprite.setTexture(texture);
    while (window.isOpen())
    {

        sf::Event evnt;
        while (window.pollEvent(evnt))
        {
            switch (evnt.type)
            {
            case sf::Event::Closed:
                window.close();
                break;
            }
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::W)) {
            Sprite.move(0.0f, -1.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::S)) {
            Sprite.move(0.0f, 1.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::A)) {
            Sprite.move(-1.0f, 0.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::D)) {
            Sprite.move(1.0f, 0.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Up)) {
            Sprite.move(0.0f, -1.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Down)) {
            Sprite.move(0.0f, 1.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Left)) {
            Sprite.move(-1.0f, 0.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Right)) {
            Sprite.move(1.0f, 0.0f);
        }
        window.setPosition(position);
        window.clear();
        window.draw(Sprite);
        window.display();
    }

    return 0;
}
</code>```

答:
Make sure that image.png is in the correct place. \Visual Studio 2015\Projects\*ProjectName*\*ProjectName*

If it is in there try and put it in the directory with the executable in it.

```<code>\Visual Studio 2015\Projects\*ProjectName*\Debug(or release)
</code>```

ContentLicense: CC BY-SA 3.0

Title: SFML Sprite not displaying

Body:
I recently started learning SFML and I am trying to display an image. The image is supposed to be displayed on the screen and be movable with arrow keys and WASD.

However, am getting a blank screen with an error Failed to load image "image.png". Reason: Unable to open file, when I display a bitmap it works. How can I fix this?

// ConsoleApplication8.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <SFML\Graphics.hpp>
#include <iostream>

int main()
{
    sf::RenderWindow window(sf::VideoMode::getDesktopMode(), "SFML works!", sf::Style::Resize | sf::Style::Default);
    sf::CircleShape shape(100.f);
    sf::Vector2i position(-9,0);
    shape.setFillColor(sf::Color::Green);
    sf::Texture texture;
    if (!texture.loadFromFile("image.png", sf::IntRect(10, 10, 32, 32)))
    {
        std::cout << "Could not load image\n";
        system("pause");

    }
    sf::Sprite Sprite;
    Sprite.setTexture(texture);
    while (window.isOpen())
    {

        sf::Event evnt;
        while (window.pollEvent(evnt))
        {
            switch (evnt.type)
            {
            case sf::Event::Closed:
                window.close();
                break;
            }
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::W)) {
            Sprite.move(0.0f, -1.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::S)) {
            Sprite.move(0.0f, 1.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::A)) {
            Sprite.move(-1.0f, 0.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::D)) {
            Sprite.move(1.0f, 0.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Up)) {
            Sprite.move(0.0f, -1.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Down)) {
            Sprite.move(0.0f, 1.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Left)) {
            Sprite.move(-1.0f, 0.0f);
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Right)) {
            Sprite.move(1.0f, 0.0f);
        }
        window.setPosition(position);
        window.clear();
        window.draw(Sprite);
        window.display();
    }

    return 0;
}

Body:
Make sure that image.png is in the correct place. \Visual Studio 2015\Projects\*ProjectName*\*ProjectName*

If it is in there try and put it in the directory with the executable in it.

\Visual Studio 2015\Projects\*ProjectName*\Debug(or release)


问:
Atmel Studio AVR operand out of range
I am working on a small program to learn how to mix C and Assembly in Atmel Studio GCC.  Basically I am writing a C program to initiate the stack pointer in assembly.  When I build it I keep getting an error "Operand out of range".  I've initiated stack pointers many times in programs but can't get it to work in the ".s" file of this program.  I've gotten the program to work with different register in the ".s" file so I don't think it's the connection between the two files.  Any help would be appreciated.

Main.c:

```<code>    #define F_CPU 16000000

    #include <avr/io.h>
    #include <util/delay.h>

    extern void setStackPointer(void);

    int main(void)
    {
        DDRB |= 0x20;
        setStackPointer();
        while (1)
        {
            PORTB = 0x20;
            _delay_ms(500);
            PORTB = 0x00;
            _delay_ms(500);
        }
    }
</code>```

Assembler1.s:

```<code>    #define _SFR_ASM_COMPAT 1
    #define _SFR_OFFSET 0
    #include <avr/io.h>

    .global setStackPointer

    setStackPointer:
                ldi r18, lo8(RAMEND-0x20)
                out SPL, R18
                ldi R18, hi8(RAMEND-0x20)
                out SPH, R18
                ret
</code>```

答:
There are several issues here.

First, the comment by Sir Jo Black is right: there is no reason to
subtract 0x20 from RAMEND. I mean, unless you want to set apart 32
bytes at the end of the RAM...

Second, there is no point in setting the stack pointer yourself. On most
recent AVRs, including the ATmega328P, SP is automatically initialized
by the hardware with RAMEND. C.f. the datasheet. If that weren't
enough, it is initialized again by the C runtime, which gets normally
linked into your program (even a 100% assembly program) if you compile
it with gcc.

Third, from the avr-libc documentation:

For more backwards compatibility, insert the following at the start of
  your old assembler source file:

#define __SFR_OFFSET 0

This automatically subtracts 0x20 from I/O space addresses, but it's a
  hack, so it is recommended to change your source: wrap such addresses
  in macros defined here, as shown below. After this is done, the
  __SFR_OFFSET definition is no longer necessary and can be removed.

The recommended way to write that code is then:

```<code>setStackPointer:
    ldi r18, lo8(RAMEND)
    out _SFR_IO_ADDR(SPL), r18
    ldi r18, hi8(RAMEND)
    out _SFR_IO_ADDR(SPH), r18
    ret
</code>```

If you really want to use the old hack, write

```<code>#define __SFR_OFFSET 0
</code>```

at the beginning of your program. And pay attention to the double
underscore at the beginning of the macro name.

Title: Atmel Studio AVR operand out of range

Body:
I am working on a small program to learn how to mix C and Assembly in Atmel Studio GCC.  Basically I am writing a C program to initiate the stack pointer in assembly.  When I build it I keep getting an error "Operand out of range".  I've initiated stack pointers many times in programs but can't get it to work in the ".s" file of this program.  I've gotten the program to work with different register in the ".s" file so I don't think it's the connection between the two files.  Any help would be appreciated.

Main.c:

    #define F_CPU 16000000

    #include <avr/io.h>
    #include <util/delay.h>

    extern void setStackPointer(void);

    int main(void)
    {
        DDRB |= 0x20;
        setStackPointer();
        while (1)
        {
            PORTB = 0x20;
            _delay_ms(500);
            PORTB = 0x00;
            _delay_ms(500);
        }
    }

Assembler1.s:

    #define _SFR_ASM_COMPAT 1
    #define _SFR_OFFSET 0
    #include <avr/io.h>

    .global setStackPointer

    setStackPointer:
                ldi r18, lo8(RAMEND-0x20)
                out SPL, R18
                ldi R18, hi8(RAMEND-0x20)
                out SPH, R18
                ret

Body:
There are several issues here.

First, the comment by Sir Jo Black is right: there is no reason to
subtract 0x20 from RAMEND. I mean, unless you want to set apart 32
bytes at the end of the RAM...

Second, there is no point in setting the stack pointer yourself. On most
recent AVRs, including the ATmega328P, SP is automatically initialized
by the hardware with RAMEND. C.f. the datasheet. If that weren't
enough, it is initialized again by the C runtime, which gets normally
linked into your program (even a 100% assembly program) if you compile
it with gcc.

Third, from the avr-libc documentation:

For more backwards compatibility, insert the following at the start of
  your old assembler source file:

#define __SFR_OFFSET 0

This automatically subtracts 0x20 from I/O space addresses, but it's a
  hack, so it is recommended to change your source: wrap such addresses
  in macros defined here, as shown below. After this is done, the
  __SFR_OFFSET definition is no longer necessary and can be removed.

The recommended way to write that code is then:

setStackPointer:
    ldi r18, lo8(RAMEND)
    out _SFR_IO_ADDR(SPL), r18
    ldi r18, hi8(RAMEND)
    out _SFR_IO_ADDR(SPH), r18
    ret

If you really want to use the old hack, write

#define __SFR_OFFSET 0

at the beginning of your program. And pay attention to the double
underscore at the beginning of the macro name.


问:
Sum not unique in R pivot table
I created a pivot table as below

```<code>library(dplyr)
Cross_LRR = filter(data_frame, data_frame$Product =="Some filter criteria")
Cross_LRR = group_by(Cross_LRR,Customer.Origin)
Cross_LRR = summarise(Cross_LRR,
                      Total_Revenue_2018 = sum(Cross_LRR$X2018),
                      Total_Revenue_2019 = sum(Cross_LRR$X2019),
                     Total_Revenue_2020 = sum(Cross_LRR$X2020))

Cross_LRR
</code>```

Cross_LRR : some place to store filtered data frame
data_frame : the data frame.

But the output of this code is like below

out put of the pivot table code I executed.

The question: Why are all the sum values the same. I know it is giving the total sum. but shouldn't it give the sum of each individual category in customer.origin?  what's wrong? what's the correct way to do this?

答:
Please share some of your data for a reproducible example, but this should work:</p>

```<code>library(dplyr)

Cross_LRR %>%
group_by(Cross_LRR,Customer.Origin) %>%
summarise(
          Total_Revenue_2018 = sum(X2018),
          Total_Revenue_2019 = sum(X2019),
          Total_Revenue_2020 = sum(X2020))
</code>```

Title: Sum not unique in R pivot table

Body:
I created a pivot table as below

library(dplyr)
Cross_LRR = filter(data_frame, data_frame$Product =="Some filter criteria")
Cross_LRR = group_by(Cross_LRR,Customer.Origin)
Cross_LRR = summarise(Cross_LRR,
                      Total_Revenue_2018 = sum(Cross_LRR$X2018),
                      Total_Revenue_2019 = sum(Cross_LRR$X2019),
                     Total_Revenue_2020 = sum(Cross_LRR$X2020))

Cross_LRR

Cross_LRR : some place to store filtered data frame
data_frame : the data frame.

But the output of this code is like below

out put of the pivot table code I executed.

The question: Why are all the sum values the same. I know it is giving the total sum. but shouldn't it give the sum of each individual category in customer.origin?  what's wrong? what's the correct way to do this?

Body:
Please share some of your data for a reproducible example, but this should work:

library(dplyr)

Cross_LRR %>%
group_by(Cross_LRR,Customer.Origin) %>%
summarise(
          Total_Revenue_2018 = sum(X2018),
          Total_Revenue_2019 = sum(X2019),
          Total_Revenue_2020 = sum(X2020))


问:
Undefined reference to GetConsoleWindow
I am trying to get a handle for the console window with the following:

```<code>#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>

#define NTDDI_WIN7 as 0x06010000
#define _WIN32_WINNT as 0x0500

int main(int argc, char *argv[]) {
    HWND self = GetConsoleWindow();
    /* some more code */
    return 0;
}
</code>```

I followed the instructions from the GetConsoleWindow documentation and "Using the Windows Headers", but I still get:

undefined reference to `GetConsoleWindow'

答: You have to have kernel32.lib in your list of input libraries.</p>

Title: Undefined reference to GetConsoleWindow

Body:
I am trying to get a handle for the console window with the following:

#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>

#define NTDDI_WIN7 as 0x06010000
#define _WIN32_WINNT as 0x0500

int main(int argc, char *argv[]) {
    HWND self = GetConsoleWindow();
    /* some more code */
    return 0;
}

I followed the instructions from the GetConsoleWindow documentation and "Using the Windows Headers", but I still get:

undefined reference to `GetConsoleWindow'


问:
AngularJS Bootstrap - push row to the next line inside ng-repeat
How can I make bootstrap "jump" to the next row inside ng-repeat.

To clarify, I have something like this:

```<code> <div class=row>
   <div class="col-sm-3" ng-repeat="field in fields">
   </div>
  </div>
</code>```

What I want is to jump to the next row based on a condition inside ng-repeat. Like this:

```<code>[1][2][3]
[4][5]
[6][7][8]
</code>```

The catch here is that I have to jump columns inside the column div.

Does anyone know the best way to solve this? Please tell me if my question isn't clear.

答:
played a bit with ng-class hope that helps
its a bit confusing how bootstrap class works with angular
http://jsfiddle.net/8n9u54ud/

js:

```<code>angular.module('app',['QuickList']).controller('mainCtrl', function($scope){

    $scope.myJson = [1,2,3,4,5,6,7,8,9]
})
</code>```

html:

```<code><div ng-app='app' ng-controller='mainCtrl'>
  <div class="row">
      <div ng-repeat="i in myJson" ng-class="{'col-sm-4':i!=5, 'col-sm-5':i==5}">
        {{i}}
      </div>
  </div>
</div>
</code>```

UPDATED

Body:
How can I make bootstrap "jump" to the next row inside ng-repeat.

To clarify, I have something like this:

What I want is to jump to the next row based on a condition inside ng-repeat. Like this:

[1][2][3]
[4][5]
[6][7][8]

The catch here is that I have to jump columns inside the column div.

Does anyone know the best way to solve this? Please tell me if my question isn't clear.

Body:
played a bit with ng-class hope that helps
its a bit confusing how bootstrap class works with angular
http://jsfiddle.net/8n9u54ud/

js:

angular.module('app',['QuickList']).controller('mainCtrl', function($scope){

    $scope.myJson = [1,2,3,4,5,6,7,8,9]
})

html:

<div ng-app='app' ng-controller='mainCtrl'>
  <div class="row">
      <div ng-repeat="i in myJson" ng-class="{'col-sm-4':i!=5, 'col-sm-5':i==5}">
        {{i}}
      </div>
  </div>
</div>

UPDATED


问:
For the fit method in LinearRegression in scikit-learn, why is the second parameter consisting of y coordinates required?
The objects of LinearRegression from sklearn.linear_model can be used to fit data point to a line. As can be seen from the code below, the fit method takes two parameters, the list of points and another list of just y coordinates. </p>

```<code>from sklearn import linear_model
reg = linear_model.LinearRegression()
reg.fit ([[0, 0], [1, 1], [2, 2]], [0, 1, 2])
</code>```

<p>My question is this: why is the second parameter even required? Is it not redundant information? </p>

答:
to fit data point to a line

It rather fits a line through your data points.

fit method takes two parameters, the list of points and another list of just y coordinates.

X are your data samples, where each row is a datapoint (one sample, a N-dimensional feature vector).
y are the datapoint labels, one per datapoint. fit method finds matrix W (feature weights) and vector b (bias), such that it minimizes distance between your prediction yhat = Wx + b and the real y.

E.g. if you are given 2-dimensional datapoints with coordinates [x,y] and you would like to predict y based on x, you pass xs as the first argument and ys as the second argument to fit.

Body:
The objects of LinearRegression from sklearn.linear_model can be used to fit data point to a line. As can be seen from the code below, the fit method takes two parameters, the list of points and another list of just y coordinates.

from sklearn import linear_model
reg = linear_model.LinearRegression()
reg.fit ([[0, 0], [1, 1], [2, 2]], [0, 1, 2])

My question is this: why is the second parameter even required? Is it not redundant information?


问:
How to create a WSResponse object from string for Play WSClient
Documentation suggests testing API client based on WSClient using a mock web service, that is, create a play.server.Server which will respond to real HTTP requests.

I would prefer to create WSResponse objects directly from files, complete with status line, header lines and body, without real TCP connections. That would require less dependencies and run faster. Also there may be other cases when this is useful.

But I can't find a simple way to do it. It seems all implementations wrapped by WSResponse are tied to reading from network.

Should I just create my own subclass of WSResponse for this, or maybe I'm wrong and it already exists?

答:
The API for Play seems intentionally obtuse. You have to use their "Cacheable" classes, which are the only ones that seem directly instantiable from objects you'd have lying around.

This should get you started:

```<code>import play.api.libs.ws.ahc.AhcWSResponse;
import play.api.libs.ws.ahc.cache.CacheableHttpResponseBodyPart;
import play.api.libs.ws.ahc.cache.CacheableHttpResponseHeaders;
import play.api.libs.ws.ahc.cache.CacheableHttpResponseStatus;
import play.shaded.ahc.io.netty.handler.codec.http.DefaultHttpHeaders;
import play.shaded.ahc.org.asynchttpclient.Response;
import play.shaded.ahc.org.asynchttpclient.uri.Uri;

AhcWSResponse response = new AhcWSResponse(new Response.ResponseBuilder()
        .accumulate(new CacheableHttpResponseStatus(Uri.create("uri"), 200, "status text", "protocols!"))
        .accumulate(new CacheableHttpResponseHeaders(false, new DefaultHttpHeaders().add("My-Header", "value")))
        .accumulate(new CacheableHttpResponseBodyPart("my body".getBytes(), true))
        .build());
</code>```

The mystery boolean values aren't documented. My guess is the boolean for BodyPart is whether that is the last part of the body. My guess for Headers is whether the headers are in the trailer of a message.

Body:
The API for Play seems intentionally obtuse. You have to use their "Cacheable" classes, which are the only ones that seem directly instantiable from objects you'd have lying around.

This should get you started:

import play.api.libs.ws.ahc.AhcWSResponse;
import play.api.libs.ws.ahc.cache.CacheableHttpResponseBodyPart;
import play.api.libs.ws.ahc.cache.CacheableHttpResponseHeaders;
import play.api.libs.ws.ahc.cache.CacheableHttpResponseStatus;
import play.shaded.ahc.io.netty.handler.codec.http.DefaultHttpHeaders;
import play.shaded.ahc.org.asynchttpclient.Response;
import play.shaded.ahc.org.asynchttpclient.uri.Uri;

AhcWSResponse response = new AhcWSResponse(new Response.ResponseBuilder()
        .accumulate(new CacheableHttpResponseStatus(Uri.create("uri"), 200, "status text", "protocols!"))
        .accumulate(new CacheableHttpResponseHeaders(false, new DefaultHttpHeaders().add("My-Header", "value")))
        .accumulate(new CacheableHttpResponseBodyPart("my body".getBytes(), true))
        .build());

The mystery boolean values aren't documented. My guess is the boolean for BodyPart is whether that is the last part of the body. My guess for Headers is whether the headers are in the trailer of a message.


问:
Disable the embedded cassandra of lagom framework
I start my first Lagom example via this command:

```<code>activator new my-first-system lagom-java
</code>```

When I tried to start this project I noticed that I have an embedded Casandra started.

So I tried to disable this one to connect to my external Cassandra instance. To do that I used:

```<code>lagomCassandraEnabled in ThisBuild := false
lagomUnmanagedServices in ThisBuild := Map("cas_native" -> "http://ip:9042")
</code>```

With this configuration, I succeed to connect to my Cassandra instance, but even that I still have a kind of heaviness in my build.

So I want to know by disabling Lagom Cassandra:

it will be started but it will be not used? or

it will be not downloaded So it will be not started?

Any help, please

答:
Cassandra will not be started when lagomCassandraEnabled in ThisBuild := false, regarding the download using Maven or Ivy will cache the libraries locally in your desktop, so probably the first build will more time but after the consecutive builds should be faster.

https://www.lagomframework.com/documentation/1.3.x/java/CassandraServer.html

You should not see the message:

[info] Starting Cassandra
and
[info] Cassandra server running at 127.0.0.1:4000 in the log...

To check detailed activity of Cassandra you can configure the logging

https://www.lagomframework.com/documentation/1.3.x/java/SettingsLogger.html

with:

  <logger name="org.apache.cassandra" level="ALL" />
  <logger name="com.datastax.driver" level="ALL" />

Body:
I start my first Lagom example via this command:

activator new my-first-system lagom-java

When I tried to start this project I noticed that I have an embedded Casandra started.

So I tried to disable this one to connect to my external Cassandra instance. To do that I used:

lagomCassandraEnabled in ThisBuild := false
lagomUnmanagedServices in ThisBuild := Map("cas_native" -> "http://ip:9042")

With this configuration, I succeed to connect to my Cassandra instance, but even that I still have a kind of heaviness in my build.

So I want to know by disabling Lagom Cassandra:

it will be started but it will be not used? or

it will be not downloaded So it will be not started?

Any help, please


问:
Error when using bitcore-explorer with bitcore-lib (Bitcore)
I am trying to use bitcore-lib to generate bitcoin address and fetch unspent transaction using bitcore-explorer..
to generate the address here is the code:

```<code>var bitcore = require('bitcore-lib');
var rand_buffer = bitcore.crypto.Random.getRandomBuffer(32);
var rand_number = bitcore.crypto.BN.fromBuffer(rand_buffer);
var privateKay = new bitcore.PrivateKey(rand_number);
var privateKeyWif = privateKay.toWIF();
var address = privateKay.toAddress('testnet');
console.log({
  rand_buffer:rand_buffer,
  rand_number_hex:rand_number,
  rand_number_dec:rand_number.toString(),
  privateKey:privateKay,
  privateKeyWif: privateKeyWif,
  address:address,
});
</code>```

Which is working fine... the output is:

```<code>{ rand_buffer: <Buffer 55 8b 27 c4 51 87 97 17 9a 7d 1d 72 48 26 e5 83 95 74 5b 3b b1 b4 b5 b6 a7 1c df 9f 18 e6 97 2e>,
  rand_number_hex: <BN: 558b27c4518797179a7d1d724826e58395745b3bb1b4b5b6a71cdf9f18e6972e>,
  rand_number_dec: '38692458332424984226826540178179935156087120588336482991409403810055901845294',
  privateKey: <PrivateKey: 558b27c4518797179a7d1d724826e58395745b3bb1b4b5b6a71cdf9f18e6972e, network: livenet>,
  privateKeyWif: 'Kz5zkBwfiYNkyswsKjot4wWmxHWUZdVMmxf65Z5wLk29ufhxnnQT',
  address: <Address: msTDjA4PmyePSWx2VcaQWoWoQ7gWzU2Kqx, type: pubkeyhash, network: testnet> }
</code>```

after doing any transaction on the generated address,
i need to use bitcore-explorers
so i requires bitcore-explorers
here is the code:

```<code>var Insight = require('bitcore-explorers').Insight;
var insight = new Insight('testnet');
insight.getUnspentUtxos(address1,(error,utxos)=>{
  if(error) return console.log(error);
  console.log(utxos)
});
</code>```

The problem is when i require bitcore-explorers it gives me following error:

```<code>D:\RAHEEL\Projects\gateway\node_modules\bitcore-explorers\node_modules\bitcore-lib\index.js:12
    throw new Error(message);
    ^

Error: More than one instance of bitcore-lib found. Please make sure to require bitcore-lib and check that submodules do not
also include their own bitcore-lib dependency.
    at Object.bitcore.versionGuard (D:\RAHEEL\Projects\gateway\node_modules\bitcore-explorers\node_modules\bitcore-lib\index.
js:12:11)
    at Object.<anonymous> (D:\RAHEEL\Projects\gateway\node_modules\bitcore-explorers\node_modules\bitcore-lib\index.js:15:9)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (D:\RAHEEL\Projects\gateway\node_modules\bitcore-explorers\lib\models\addressinfo.js:3:15)
</code>```

答:
There is a temp solution here.

~/bitcore-explorers/node_modules/bitcore-lib/index.js

line 7:

```<code>bitcore.versionGuard = function(version) {
</code>```

Change it to:

```<code>bitcore.versionGuard = function(version) { return;
</code>```

However this issue should be fixed for main branch which is not yet fixed currently. You can check this here

Body:
I am trying to use bitcore-lib to generate bitcoin address and fetch unspent transaction using bitcore-explorer..
to generate the address here is the code:

var bitcore = require('bitcore-lib');
var rand_buffer = bitcore.crypto.Random.getRandomBuffer(32);
var rand_number = bitcore.crypto.BN.fromBuffer(rand_buffer);
var privateKay = new bitcore.PrivateKey(rand_number);
var privateKeyWif = privateKay.toWIF();
var address = privateKay.toAddress('testnet');
console.log({
  rand_buffer:rand_buffer,
  rand_number_hex:rand_number,
  rand_number_dec:rand_number.toString(),
  privateKey:privateKay,
  privateKeyWif: privateKeyWif,
  address:address,
});

Which is working fine... the output is:

{ rand_buffer: <Buffer 55 8b 27 c4 51 87 97 17 9a 7d 1d 72 48 26 e5 83 95 74 5b 3b b1 b4 b5 b6 a7 1c df 9f 18 e6 97 2e>,
  rand_number_hex: <BN: 558b27c4518797179a7d1d724826e58395745b3bb1b4b5b6a71cdf9f18e6972e>,
  rand_number_dec: '38692458332424984226826540178179935156087120588336482991409403810055901845294',
  privateKey: <PrivateKey: 558b27c4518797179a7d1d724826e58395745b3bb1b4b5b6a71cdf9f18e6972e, network: livenet>,
  privateKeyWif: 'Kz5zkBwfiYNkyswsKjot4wWmxHWUZdVMmxf65Z5wLk29ufhxnnQT',
  address: <Address: msTDjA4PmyePSWx2VcaQWoWoQ7gWzU2Kqx, type: pubkeyhash, network: testnet> }

after doing any transaction on the generated address,
i need to use bitcore-explorers
so i requires bitcore-explorers
here is the code:

var Insight = require('bitcore-explorers').Insight;
var insight = new Insight('testnet');
insight.getUnspentUtxos(address1,(error,utxos)=>{
  if(error) return console.log(error);
  console.log(utxos)
});

The problem is when i require bitcore-explorers it gives me following error:

D:\RAHEEL\Projects\gateway\node_modules\bitcore-explorers\node_modules\bitcore-lib\index.js:12
    throw new Error(message);
    ^

Error: More than one instance of bitcore-lib found. Please make sure to require bitcore-lib and check that submodules do not
also include their own bitcore-lib dependency.
    at Object.bitcore.versionGuard (D:\RAHEEL\Projects\gateway\node_modules\bitcore-explorers\node_modules\bitcore-lib\index.
js:12:11)
    at Object.<anonymous> (D:\RAHEEL\Projects\gateway\node_modules\bitcore-explorers\node_modules\bitcore-lib\index.js:15:9)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (D:\RAHEEL\Projects\gateway\node_modules\bitcore-explorers\lib\models\addressinfo.js:3:15)

Body:
There is a temp solution here.

~/bitcore-explorers/node_modules/bitcore-lib/index.js

line 7:

bitcore.versionGuard = function(version) {

Change it to:

bitcore.versionGuard = function(version) { return;

However this issue should be fixed for main branch which is not yet fixed currently. You can check this here


问:
Tkinter : I need to stop generating this "main" function called "pyrotechnik" when i press any button
Hi guys I'm new to programming and I'm working with python at school.
Currently I'm working with tkinter and I have a little problem with this exercise.
Timer starts at 60, when it hits 0, it "explodes". If i click the right wire, it will tell me i've made it but if i click the wrong one it "explodes". The problem is, when i click any button it keeps generating the main function and I have no idea how to stop it. I hope someone can help me :)</p>

```<code>import tkinter
from random import *
canvas = tkinter.Canvas(bg='White', width=400, height=200)
canvas.pack()

stop = randint(1, 4)
timer = 61

def pyrotechnik():
    global timer, stop
    canvas.delete('all')
    timer -= 1
    canvas.create_text(200, 100, font='Arial 20 bold', text=timer, fill='Red')
    if timer == 0:
        canvas.delete('all')
        canvas.create_text(200, 100, font='Arial 20 bold', text='Bomb has exploded', fill='Red')
    else:
        canvas.after(1000, pyrotechnik)
print(stop)

def blue():
    canvas.delete('all')
    if stop == 1:
        canvas.create_text(200, 100, font='Arial 20 bold', text='Thank god you"ve made it', fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM', fill='Orange')
def red():
    canvas.delete('all')
    if stop == 2:
        canvas.create_text(200, 100, font='Arial 20 bold', text='Thank god you"ve made it', fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM', fill='Orange')

def yellow():
    canvas.delete('all')
    if stop == 3:
        canvas.create_text(200, 100, font='Arial 20 bold', text='Thank god you"ve made it', fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM', fill='Orange')

def green():
    canvas.delete('all')
    if stop == 4:
        canvas.create_text(200, 100, font='Arial 20 bold', text='Thank god you"ve made it', fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM', fill='Orange')

button1 = tkinter.Button(text='Blue wire', command=blue, bg='SkyBlue') button1.pack()

button2 = tkinter.Button(text='Red wire', command=red, bg='Red') button2.pack()

button3 = tkinter.Button(text='Yellow wire', command=yellow, bg='Yellow') button3.pack()

button4 = tkinter.Button(text='Green wire', command=green, bg='Green') button4.pack()

pyrotechnik()
</code>```

答:
If you want to create GUI applications, you would do well to learn about object-oriented programming. Designing your programs with classes helps keep your code organized if used properly. While my previous answer may have worked fine for what you were trying to accomplish, my recommendation would be to learn how to write your code in the following way instead:</p>

```<code>#! /usr/bin/env python3
import random
import tkinter
import tkinter.font

class Pyrotechnic(tkinter.Frame):
    __DEFAULT = object()

    @classmethod
    def main(cls):
        tkinter.NoDefaultRoot()
        root = tkinter.Tk()
        root.title(cls.__name__)
        root.resizable(False, False)
        self = cls(root)
        self.grid()
        root.mainloop()

    def __init__(self, master=None, cnf=__DEFAULT, **kw):
        if cnf is self.__DEFAULT:
            cnf = {}
        super().__init__(master, cnf, **kw)
        self.canvas = tkinter.Canvas(self, bg='#FFFFFF', width=400, height=200)
        self.canvas.grid(sticky=tkinter.NSEW)
        self.stop = random.randint(1, 4)
        self.timer = 60
        self.buttons = []
        for wire_id, (name, color) in enumerate((
                ('Blue', '#7777FF'),
                ('Red', '#FF0000'),
                ('Yellow', '#FFFF00'),
                ('Green', '#00FF00')), 1):
            new_button = tkinter.Button(
                self,
                text=f'{name} Wire',
                command=self.create_button_handler(wire_id),
                bg=color
            )
            new_button.grid(sticky=tkinter.NSEW, padx=5, pady=5)
            self.buttons.append(new_button)
        self.after_handle = None
        self.font = tkinter.font.Font(
            self,
            family='Arial',
            size=20,
            weight='bold'
        )
        self.game_over = False
        self.timer_loop()

    def echo(self, text, fill):
        self.canvas.create_text(200, 100, font=self.font, text=text, fill=fill)

    def create_button_handler(self, wire_id):
        def button_handler():
            if not self.game_over:
                self.canvas.delete(tkinter.ALL)
                self.after_cancel(self.after_handle)
                if self.stop == wire_id:
                    self.echo("Thank god you've made it!", '#00FF00')
                else:
                    self.echo('BOOM', '#FF7700')
                self.game_over = True

        return button_handler

    def timer_loop(self):
        self.canvas.delete(tkinter.ALL)
        if self.timer > 0:
            self.echo(self.timer, '#FF0000')
            self.timer -= 1
            self.after_handle = self.after(1000, self.timer_loop)
        else:
            self.echo('Bomb has exploded!', '#FF0000')
            self.game_over = True

if __name__ == '__main__':
    Pyrotechnic.main()
</code>```

Body:
Hi guys I'm new to programming and I'm working with python at school.
Currently I'm working with tkinter and I have a little problem with this exercise.
Timer starts at 60, when it hits 0, it "explodes". If i click the right wire, it will tell me i've made it but if i click the wrong one it "explodes". The problem is, when i click any button it keeps generating the main function and I have no idea how to stop it. I hope someone can help me :)

import tkinter
from random import *
canvas = tkinter.Canvas(bg='White', width=400, height=200)
canvas.pack()

stop = randint(1, 4)
timer = 61

def pyrotechnik():
    global timer, stop
    canvas.delete('all')
    timer -= 1
    canvas.create_text(200, 100, font='Arial 20 bold', text=timer, fill='Red')
    if timer == 0:
        canvas.delete('all')
        canvas.create_text(200, 100, font='Arial 20 bold', text='Bomb has exploded', fill='Red')
    else:
        canvas.after(1000, pyrotechnik)
print(stop)

def blue():
    canvas.delete('all')
    if stop == 1:
        canvas.create_text(200, 100, font='Arial 20 bold', text='Thank god you"ve made it', fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM', fill='Orange')
def red():
    canvas.delete('all')
    if stop == 2:
        canvas.create_text(200, 100, font='Arial 20 bold', text='Thank god you"ve made it', fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM', fill='Orange')

def yellow():
    canvas.delete('all')
    if stop == 3:
        canvas.create_text(200, 100, font='Arial 20 bold', text='Thank god you"ve made it', fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM', fill='Orange')

def green():
    canvas.delete('all')
    if stop == 4:
        canvas.create_text(200, 100, font='Arial 20 bold', text='Thank god you"ve made it', fill='Green')
    else:
        canvas.create_text(200, 100, font='Arial 20 bold', text='BOOM', fill='Orange')

button1 = tkinter.Button(text='Blue wire', command=blue, bg='SkyBlue') button1.pack()

button2 = tkinter.Button(text='Red wire', command=red, bg='Red') button2.pack()

button3 = tkinter.Button(text='Yellow wire', command=yellow, bg='Yellow') button3.pack()

button4 = tkinter.Button(text='Green wire', command=green, bg='Green') button4.pack()

pyrotechnik()

Body:
If you want to create GUI applications, you would do well to learn about object-oriented programming. Designing your programs with classes helps keep your code organized if used properly. While my previous answer may have worked fine for what you were trying to accomplish, my recommendation would be to learn how to write your code in the following way instead:

#! /usr/bin/env python3
import random
import tkinter
import tkinter.font

class Pyrotechnic(tkinter.Frame):
    __DEFAULT = object()

    @classmethod
    def main(cls):
        tkinter.NoDefaultRoot()
        root = tkinter.Tk()
        root.title(cls.__name__)
        root.resizable(False, False)
        self = cls(root)
        self.grid()
        root.mainloop()

    def __init__(self, master=None, cnf=__DEFAULT, **kw):
        if cnf is self.__DEFAULT:
            cnf = {}
        super().__init__(master, cnf, **kw)
        self.canvas = tkinter.Canvas(self, bg='#FFFFFF', width=400, height=200)
        self.canvas.grid(sticky=tkinter.NSEW)
        self.stop = random.randint(1, 4)
        self.timer = 60
        self.buttons = []
        for wire_id, (name, color) in enumerate((
                ('Blue', '#7777FF'),
                ('Red', '#FF0000'),
                ('Yellow', '#FFFF00'),
                ('Green', '#00FF00')), 1):
            new_button = tkinter.Button(
                self,
                text=f'{name} Wire',
                command=self.create_button_handler(wire_id),
                bg=color
            )
            new_button.grid(sticky=tkinter.NSEW, padx=5, pady=5)
            self.buttons.append(new_button)
        self.after_handle = None
        self.font = tkinter.font.Font(
            self,
            family='Arial',
            size=20,
            weight='bold'
        )
        self.game_over = False
        self.timer_loop()

    def echo(self, text, fill):
        self.canvas.create_text(200, 100, font=self.font, text=text, fill=fill)

    def create_button_handler(self, wire_id):
        def button_handler():
            if not self.game_over:
                self.canvas.delete(tkinter.ALL)
                self.after_cancel(self.after_handle)
                if self.stop == wire_id:
                    self.echo("Thank god you've made it!", '#00FF00')
                else:
                    self.echo('BOOM', '#FF7700')
                self.game_over = True

        return button_handler

    def timer_loop(self):
        self.canvas.delete(tkinter.ALL)
        if self.timer > 0:
            self.echo(self.timer, '#FF0000')
            self.timer -= 1
            self.after_handle = self.after(1000, self.timer_loop)
        else:
            self.echo('Bomb has exploded!', '#FF0000')
            self.game_over = True

if __name__ == '__main__':
    Pyrotechnic.main()


问:
Safe use of HttpURLConnection
When using HttpURLConnection does the InputStream need to be closed if we do not 'get' and use it?

i.e. is this safe?

```<code>HttpURLConnection conn = (HttpURLConnection) uri.getURI().toURL().openConnection();
conn.connect();
// check for content type I don't care about
if (conn.getContentType.equals("image/gif") return;
// get stream and read from it
InputStream is = conn.getInputStream();
try {
    // read from is
} finally {
    is.close();
}
</code>```

Secondly, is it safe to close an InputStream before all of it's content has been fully read?

Is there a risk of leaving the underlying socket in ESTABLISHED or even CLOSE_WAIT state?

答:
If you really want to make sure that the connection is close you should call conn.disconnect().

The open connections you observed are because of the HTTP 1.1 connection keep alive feature (also known as HTTP Persistent Connections).
If the server supports HTTP 1.1 and does not send a Connection: close in the response header Java does not immediately close the underlaying TCP connection when you close the input stream. Instead it keeps it open and tries to reuse it for the next HTTP request to the same server.

If you don't want this behaviour at all you can set the system property http.keepAlive to false:

```<code>System.setProperty("http.keepAlive","false");
</code>```

ContentLicense: CC BY-SA 2.5

Title: Safe use of HttpURLConnection

Body:
When using HttpURLConnection does the InputStream need to be closed if we do not 'get' and use it?

i.e. is this safe?

HttpURLConnection conn = (HttpURLConnection) uri.getURI().toURL().openConnection();
conn.connect();
// check for content type I don't care about
if (conn.getContentType.equals("image/gif") return;
// get stream and read from it
InputStream is = conn.getInputStream();
try {
    // read from is
} finally {
    is.close();
}

Secondly, is it safe to close an InputStream before all of it's content has been fully read?

Is there a risk of leaving the underlying socket in ESTABLISHED or even CLOSE_WAIT state?

Body:
If you really want to make sure that the connection is close you should call conn.disconnect().

The open connections you observed are because of the HTTP 1.1 connection keep alive feature (also known as HTTP Persistent Connections).
If the server supports HTTP 1.1 and does not send a Connection: close in the response header Java does not immediately close the underlaying TCP connection when you close the input stream. Instead it keeps it open and tries to reuse it for the next HTTP request to the same server.

If you don't want this behaviour at all you can set the system property http.keepAlive to false:

System.setProperty("http.keepAlive","false");


问:
How to set elasticsearch index.mapping.total_fields.limit to unlimited
I am dealing with a huge json blob so I need to open the seal. How can I set elasticsearch index.mapping.total_fields.limit to unlimited?

答:
You cannot set it to unlimited. In fact, it has been intentionally limited to prevent mapping explosion. You can read the the github issue here.

The only to achieve what you want is by using a high value.

You can specify that value when creating the index:

```<code>PUT test
{
  "shopfront": {
    "index.mapping.total_fields.limit": 2000,
    "number_of_shards": 5,
    "number_of_replicas": 2
  },
  "mappings": {
    ...
  }
}
</code>```

Or if it is for an existing index:

```<code>PUT shopfront/_settings
{
  "index.mapping.total_fields.limit": 2000
}
</code>```

Body:
You cannot set it to unlimited. In fact, it has been intentionally limited to prevent mapping explosion. You can read the the github issue here.

The only to achieve what you want is by using a high value.

You can specify that value when creating the index:

PUT test
{
  "shopfront": {
    "index.mapping.total_fields.limit": 2000,
    "number_of_shards": 5,
    "number_of_replicas": 2
  },
  "mappings": {
    ...
  }
}

Or if it is for an existing index:

PUT shopfront/_settings
{
  "index.mapping.total_fields.limit": 2000
}


问:
Weird behaviour with crontab an flock
I'm trying to run only one instance of a program, this is my runner script which is called from crontab:

```<code>#!/bin/bash

exec 9>./lockfile
if ! flock -n 9  ; then
   echo "another instance of $0 is running";
   exit 1
fi

node $(dirname $0)/init.js
</code>```

The line in crontab is as follows:

```<code>*/5 * * * * /bin/bash /path/to/proyect/runner.sh >> /path/to/proyect/logs/output.log 2>> /path/to/proyect/logs/error.log
</code>```

The weird thing is that after I kill the process the file stays locked

答: Weirdly enough opening the file in vim and saving it unlocks the file. This only happens when killing the process from the cli with kill -9 pid

Title: Weird behaviour with crontab an flock

Body:
I'm trying to run only one instance of a program, this is my runner script which is called from crontab:

#!/bin/bash

exec 9>./lockfile
if ! flock -n 9  ; then
   echo "another instance of $0 is running";
   exit 1
fi

node $(dirname $0)/init.js

The line in crontab is as follows:

*/5 * * * * /bin/bash /path/to/proyect/runner.sh >> /path/to/proyect/logs/output.log 2>> /path/to/proyect/logs/error.log

The weird thing is that after I kill the process the file stays locked


问:
Go To Definition: "Cannot navigate to the symbol under the caret."
I suddenly started experiencing a problem today in my project where clicking Go To Definition gives me a strange error: "Cannot navigate to the symbol under the caret."

I first noticed it some time after installing Costura.Fody via NuGet. I've since uninstalled it but the problem persists. I've cleaned and rebuilt the solution multiple times. There are no instances of "Fody" or "Costura" anywhere in my git commit history, before or after the point in time when this started happening, so I'm thinking that one of my .gitignore'd files is stuck in a bad state.

The problem only occurs if the definition being targeted is in another file; Go To Definition for something in the currently opened file works fine. Peek Definition works fine too. Other solutions/projects work fine as well -- it's only this one that's causing issues.

I'm using Visual Studio 2015. The issue doesn't seem to occur in the 2013 version.

Why does this error occur and how can I fix it?

答:
Recently upgraded to VS 2017 15.5.0 and came across this problem. I tried:

Deleting the symbol cache

Deleting my .vs folder.

Rebuilding solution.

Running devenv /resetuserdata

Sadly, none of these worked. I noticed that this was only happening on some projects and not others. On the project where it was failing, I ended up switching all of the framework versions to 4.7.1, did a clean/rebuild and my "Go to Definition" started working again.


问:
Search a Dynamic Number of rows in Column A for a specific string in VBA
I have a worksheet that contains a varying amount of Rows of data in Column A , within this worksheet I need to search for a specific string then copy the data contained in the Cell adjacent to it and paste into Column C, i.e if data was found in A2 then i need to copy the data from B2 and paste into C1. I can easily find and copy when the string appears once but the string will appear more than once 100% of time. here is when i run into issues.

The temporary code I have written for ease of understanding, searches the spreadsheet for the last Mention of A, get the row number, copy the B cell for that row number then pastes the value into C1.

I guess you need to use range variables for this but not 100% sure how to do it.

i have found no way to copy all mentions of A into a column, or ideally sum up the contents of the B cells. (I can do this, just long winded)

Ive placed my code below.

```<code>Sub ValueFinder()
Dim LastALocation As String
Dim ValueContent As String

LastALocation = Range("A:A").Find(What:="A", after:=Range("A1"), searchdirection:=xlPrevious).Row
ValueContent = Cells(LastALocation, 2)
Cells(1, 3) = ValueContent

End Sub
</code>```

The spreadsheet that its using for more information, contains A,B,C on a loop in Column A and the odd numbers in Column B.

Thanks for any help your able to provide.

Mark

答:
This will look for a string in Column A, and add to Column C the same row's B Column Value.

```<code>Sub find_move()
Dim foundCel As Range
Dim findStr As String, firstAddress As String
Dim i As Long
i = 1
findStr = "A"
Set foundCel = Range("A:A").Find(what:=findStr)
If Not foundCel Is Nothing Then
    firstAddress = foundCel.Address
    Do
        Range("C" & i).Value = foundCel.Offset(0, 1).Value
        Set foundCel = Range("A:A").FindNext(foundCel)
        i = i + 1
    Loop While Not foundCel Is Nothing And foundCel.Address <> firstAddress
End If
End Sub
</code>```

Note: You should add the worksheet in front of all the range values, i.e. Sheets("Sheet1").Range("A:A").Find(...

Body:
I have a worksheet that contains a varying amount of Rows of data in Column A , within this worksheet I need to search for a specific string then copy the data contained in the Cell adjacent to it and paste into Column C, i.e if data was found in A2 then i need to copy the data from B2 and paste into C1. I can easily find and copy when the string appears once but the string will appear more than once 100% of time. here is when i run into issues.

The temporary code I have written for ease of understanding, searches the spreadsheet for the last Mention of A, get the row number, copy the B cell for that row number then pastes the value into C1.

I guess you need to use range variables for this but not 100% sure how to do it.

i have found no way to copy all mentions of A into a column, or ideally sum up the contents of the B cells. (I can do this, just long winded)

Ive placed my code below.

Sub ValueFinder()
Dim LastALocation As String
Dim ValueContent As String

LastALocation = Range("A:A").Find(What:="A", after:=Range("A1"), searchdirection:=xlPrevious).Row
ValueContent = Cells(LastALocation, 2)
Cells(1, 3) = ValueContent

End Sub

The spreadsheet that its using for more information, contains A,B,C on a loop in Column A and the odd numbers in Column B.

Thanks for any help your able to provide.

Mark

Body:
This will look for a string in Column A, and add to Column C the same row's B Column Value.

Sub find_move()
Dim foundCel As Range
Dim findStr As String, firstAddress As String
Dim i As Long
i = 1
findStr = "A"
Set foundCel = Range("A:A").Find(what:=findStr)
If Not foundCel Is Nothing Then
    firstAddress = foundCel.Address
    Do
        Range("C" & i).Value = foundCel.Offset(0, 1).Value
        Set foundCel = Range("A:A").FindNext(foundCel)
        i = i + 1
    Loop While Not foundCel Is Nothing And foundCel.Address <> firstAddress
End If
End Sub

Note: You should add the worksheet in front of all the range values, i.e. Sheets("Sheet1").Range("A:A").Find(...


问:
Symfony raw sql query returns empty array
When I'am passing $id variable in bindValue('id', $id) it shows empty array but when I pass number in bindValue('id', 2) ,I'm getting the result in array.

```<code>$em = $this->getDoctrine()->getManager();
$connection = $em->getConnection();
$statement = $connection->prepare("SELECT s.subtitle FROM submenu as s where s.menu_id= :id");
$statement->bindValue('id', $id);
$statement->execute();
$results = $statement->fetchAll();
dump($results);
</code>```

Please could anybody tell me whats my mistake in above code. I am getting empty result if I pass variable in bindvalue function but if I use this bindValue('id',2) I'm getting result.

答:
If $id is an integer the it should work but if not then may be some whitespace is coming in your variable (for example $id = ' 4redtr54r')
In this case you will get null value so can you please check your variable before assigning or use trim() function </p>

```<code>$statement->bindValue('id', trim($id));
</code>```

Body:
When I'am passing $id variable in bindValue('id', $id) it shows empty array but when I pass number in bindValue('id', 2) ,I'm getting the result in array.

$em = $this->getDoctrine()->getManager();
$connection = $em->getConnection();
$statement = $connection->prepare("SELECT s.subtitle FROM submenu as s where s.menu_id= :id");
$statement->bindValue('id', $id);
$statement->execute();
$results = $statement->fetchAll();
dump($results);

Please could anybody tell me whats my mistake in above code. I am getting empty result if I pass variable in bindvalue function but if I use this bindValue('id',2) I'm getting result.

Body:
If $id is an integer the it should work but if not then may be some whitespace is coming in your variable (for example $id = ' 4redtr54r')
In this case you will get null value so can you please check your variable before assigning or use trim() function

$statement->bindValue('id', trim($id));


问:
Create a Hibernate schema not automatically, but with SQL script
In my project I use h2 in memory database, and I want it to be created not by Hibernate, but with by a SQL script. Here is my hibernate.properties

I made

```<code>hibernate.hbm2ddl.auto=none
</code>```

none to disable autocreation of database, and added

```<code>hibernate.hbm2ddl.import_files=schema.sql,insert-users.sql
</code>```

schema.sql contains SQL code to create schema, and then to insert-users.sql and it contains the initial data.

The project builds successfully, but when I try to hit database, I get
a Table <tablename> not found exception.

答:
Two comments from the Hibernate documentation are relevant here:

```<code>This is useful for testing or demoing: by adding INSERT statements for example you can populate your database with a minimal set of data when it is deployed.
</code>```

and

```<code>These statements are only executed if the schema is created ie if hibernate.hbm2ddl.auto is set to create or create-drop.
</code>```

I'm not too sure that the import functionality will do what you want it to do.

Body:
In my project I use h2 in memory database, and I want it to be created not by Hibernate, but with by a SQL script. Here is my hibernate.properties

I made

hibernate.hbm2ddl.auto=none

none to disable autocreation of database, and added

hibernate.hbm2ddl.import_files=schema.sql,insert-users.sql

schema.sql contains SQL code to create schema, and then to insert-users.sql and it contains the initial data.

The project builds successfully, but when I try to hit database, I get
a Table <tablename> not found exception.

Body:
Two comments from the Hibernate documentation are relevant here:

This is useful for testing or demoing: by adding INSERT statements for example you can populate your database with a minimal set of data when it is deployed.

and

These statements are only executed if the schema is created ie if hibernate.hbm2ddl.auto is set to create or create-drop.

I'm not too sure that the import functionality will do what you want it to do.


问:
Mocking a method with other methods
I have the following method that I want to test:

```<code>public boolean sendMessage(Agent destinationAgent, String message, Supervisor s, MessagingSystem msgsys, String time) throws ParseException {
    if(mailbox.getMessages().size() > 25){
        return false;
    }else{
        if(login(s, msgsys, time)){
            try {
                sentMessage = msgsys.sendMessage(sessionkey, this, destinationAgent, message);
                if(sentMessage.equals("OK")) {
                    return true;
                }
                return false;
            } catch (ParseException e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }
}
</code>```

I want to mock the method login(s, msgsys, time). I am doing this as follows:

```<code>@Mock
private Supervisor supervisor;
@Mock
private MessagingSystem msgsys;

@Test
public void testSendMessageSuccess() throws ParseException {
    String message = "Hey";
    Agent destination = new Agent("Alex", "2");
    agent.sessionkey = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";

    when(agent.login(supervisor, msgsys, anyString())).thenReturn(true);
    when(msgsys.sendMessage(agent.sessionkey, destination, agent, message)).thenReturn("OK");

    boolean result = agent.sendMessage(destination, message, supervisor, msgsys, time);

    assertEquals(true, result);
}
</code>```

However, the following error is encountered:

```<code>org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
Boolean cannot be returned by getLoginKey()
getLoginKey() should return String
</code>```

Please do note that the method getLoginKey() - returns a String, is called inside the method login(s, msgsys, time), and it belongs to an interface class.

```<code>@Before
public void setup(){
    MockitoAnnotations.initMocks(this);
    agent = new Agent("David", "1");
    time = dateFormat.format(new Date());
}

@After
public void teardown(){
    agent = null;
}
</code>```

答:
If you want to mock one of the methods of Agent (login() in your case) then the Agent you are trying to stub needs to be a mock or a spy.

Since in your case login() is the only method you want to mock with the rest of the functionality of the Agent class intact then you should make a spy of this object:

```<code>@Before
public void setup(){
    MockitoAnnotations.initMocks(this);
    agent = Mockito.spy(new Agent("David", "1"));
    time = dateFormat.format(new Date());
}
</code>```

Note that when stubbing spies to you need to use the following syntax:

```<code>doReturn(true).when(agent).login(supervisor, msgsys, anyString());
</code>```

Title: Mocking a method with other methods

Body:
I have the following method that I want to test:

public boolean sendMessage(Agent destinationAgent, String message, Supervisor s, MessagingSystem msgsys, String time) throws ParseException {
    if(mailbox.getMessages().size() > 25){
        return false;
    }else{
        if(login(s, msgsys, time)){
            try {
                sentMessage = msgsys.sendMessage(sessionkey, this, destinationAgent, message);
                if(sentMessage.equals("OK")) {
                    return true;
                }
                return false;
            } catch (ParseException e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }
}

I want to mock the method login(s, msgsys, time). I am doing this as follows:

@Mock
private Supervisor supervisor;
@Mock
private MessagingSystem msgsys;

@Test
public void testSendMessageSuccess() throws ParseException {
    String message = "Hey";
    Agent destination = new Agent("Alex", "2");
    agent.sessionkey = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";

    when(agent.login(supervisor, msgsys, anyString())).thenReturn(true);
    when(msgsys.sendMessage(agent.sessionkey, destination, agent, message)).thenReturn("OK");

    boolean result = agent.sendMessage(destination, message, supervisor, msgsys, time);

    assertEquals(true, result);
}

However, the following error is encountered:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
Boolean cannot be returned by getLoginKey()
getLoginKey() should return String

Please do note that the method getLoginKey() - returns a String, is called inside the method login(s, msgsys, time), and it belongs to an interface class.

@Before
public void setup(){
    MockitoAnnotations.initMocks(this);
    agent = new Agent("David", "1");
    time = dateFormat.format(new Date());
}

@After
public void teardown(){
    agent = null;
}

Body:
If you want to mock one of the methods of Agent (login() in your case) then the Agent you are trying to stub needs to be a mock or a spy.

Since in your case login() is the only method you want to mock with the rest of the functionality of the Agent class intact then you should make a spy of this object:

@Before
public void setup(){
    MockitoAnnotations.initMocks(this);
    agent = Mockito.spy(new Agent("David", "1"));
    time = dateFormat.format(new Date());
}

Note that when stubbing spies to you need to use the following syntax:

doReturn(true).when(agent).login(supervisor, msgsys, anyString());


问:
Camel - How to stop route execution on exception?
Is there any way I can stop the route execution (after displaying a log message) when exception is caught?

```<code>        <doTry>
            <process ref="messageProcessor"/>
            <doCatch>
                <exception>java.lang.IllegalArgumentException</exception>
                <log message="some message related to the exception" />
            </doCatch>
        </doTry>
</code>```

Please provide a way to achieve this in Spring DSL. I've already tried < stop/> but that doesn't display log message.

答:
There are many ways to approach this. In addition to the accepted answer you may also want to use one of the following:

```<code>onException(SomeException.class)
.log("Uh oh...")
.stop()
</code>```

within your DSL

or:

```<code>exchange.setProperty(Exchange.ROUTE_STOP, Boolean.TRUE);
</code>```

within your Processor()

Have a look at the official documentation on this topic here: http://camel.apache.org/intercept.html

Body:
Is there any way I can stop the route execution (after displaying a log message) when exception is caught?

        <doTry>
            <process ref="messageProcessor"/>
            <doCatch>
                <exception>java.lang.IllegalArgumentException</exception>
                <log message="some message related to the exception" />
            </doCatch>
        </doTry>

Please provide a way to achieve this in Spring DSL. I've already tried < stop/> but that doesn't display log message.

Body:
There are many ways to approach this. In addition to the accepted answer you may also want to use one of the following:

onException(SomeException.class)
.log("Uh oh...")
.stop()

within your DSL

or:

exchange.setProperty(Exchange.ROUTE_STOP, Boolean.TRUE);

within your Processor()

Have a look at the official documentation on this topic here: http://camel.apache.org/intercept.html


问:
Django: How can I access celery flower page in production mode?
In development mode(local), it is really easy to access flower page (http://localhost:5555)

But in production mode, it is difficult to access flower page.

I'd like to access flower dashboard page with this url:

https://spacegraphy.choislaw.xyz/flower/ (Domain name : choislaw.xyz)

I refered http://flower.readthedocs.io/en/latest/reverse-proxy.html#reverse-proxy and this is what I did:

nginx.conf

```<code>  http {
      include       mime.types;
      default_type  application/octet-stream;
      sendfile        on;

      server {
          listen       80;
          server_name  spacegraphy.choislaw.xyz;

          client_max_body_size 4G;
          keepalive_timeout 5;

          return 301 https://$server_name$request_uri;
      }

      # HTTPS server
      server {
          listen       443 default_server ssl;
          server_name  spacegraphy.choislaw.xyz;

          client_max_body_size 4G;
          keepalive_timeout 5;

          ssl_certificate      /etc/letsencrypt/live/spacegraphy.choislaw.xyz/fullchain.pem;
          ssl_certificate_key  /etc/letsencrypt/live/spacegraphy.choislaw.xyz/privkey.pem;

          location / {
              proxy_pass_header X-CSRFToken;
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_set_header X-Forwarded-Proto https;
              proxy_set_header X-Real-IP $remote_addr;
              proxy_set_header HOST $http_host;
              proxy_set_header X-NginX-Proxy true;

              proxy_pass http://127.0.0.1:4349;
              proxy_redirect off;
          }

          # Flower
          location /flower/ {
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_set_header X-Forwarded-Proto https;
              proxy_set_header X-Real-IP $remote_addr;
              proxy_set_header HOST $http_host;
              proxy_set_header Upgrade $http_upgrade;
              proxy_set_header Connection "upgrade";
              proxy_http_version 1.1;

             proxy_pass http://localhost:5555/;
             proxy_redirect off;
         }
     }
 }
</code>```

And I execute flower server:

```<code>$ celery --workdir=spacegraphy/  --app=spacegraphy.celery:app flower
</code>```

And I access https://spacegraphy.choislaw.xyz/flower/, it shows like this:

And If I click any link,

Did I miss something? Do I separate flower server from application server?

Btw, Is it usual to run flower server on production server?

答:
you need change flower nginx conf to:</p>

```<code>location ~ ^/flower/? {
    rewrite ^/flower/?(.*)$ /$1 break;

    sub_filter '="/' '="/flower/';
    sub_filter_last_modified on;
    sub_filter_once off;

    # proxy_pass http://unix:/tmp/flower.sock:/;
    proxy_pass http://localhost:5555;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_http_version 1.1;
}
</code>```

Body:
In development mode(local), it is really easy to access flower page (http://localhost:5555)

But in production mode, it is difficult to access flower page.

I'd like to access flower dashboard page with this url:

https://spacegraphy.choislaw.xyz/flower/ (Domain name : choislaw.xyz)

I refered http://flower.readthedocs.io/en/latest/reverse-proxy.html#reverse-proxy and this is what I did:

nginx.conf

  http {
      include       mime.types;
      default_type  application/octet-stream;
      sendfile        on;

      server {
          listen       80;
          server_name  spacegraphy.choislaw.xyz;

          client_max_body_size 4G;
          keepalive_timeout 5;

          return 301 https://$server_name$request_uri;
      }

      # HTTPS server
      server {
          listen       443 default_server ssl;
          server_name  spacegraphy.choislaw.xyz;

          client_max_body_size 4G;
          keepalive_timeout 5;

          ssl_certificate      /etc/letsencrypt/live/spacegraphy.choislaw.xyz/fullchain.pem;
          ssl_certificate_key  /etc/letsencrypt/live/spacegraphy.choislaw.xyz/privkey.pem;

          location / {
              proxy_pass_header X-CSRFToken;
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_set_header X-Forwarded-Proto https;
              proxy_set_header X-Real-IP $remote_addr;
              proxy_set_header HOST $http_host;
              proxy_set_header X-NginX-Proxy true;

              proxy_pass http://127.0.0.1:4349;
              proxy_redirect off;
          }

          # Flower
          location /flower/ {
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_set_header X-Forwarded-Proto https;
              proxy_set_header X-Real-IP $remote_addr;
              proxy_set_header HOST $http_host;
              proxy_set_header Upgrade $http_upgrade;
              proxy_set_header Connection "upgrade";
              proxy_http_version 1.1;

             proxy_pass http://localhost:5555/;
             proxy_redirect off;
         }
     }
 }

And I execute flower server:

$ celery --workdir=spacegraphy/  --app=spacegraphy.celery:app flower

And I access https://spacegraphy.choislaw.xyz/flower/, it shows like this:

And If I click any link,

Did I miss something? Do I separate flower server from application server?

Btw, Is it usual to run flower server on production server?

Body:
you need change flower nginx conf to:

location ~ ^/flower/? {
    rewrite ^/flower/?(.*)$ /$1 break;

    sub_filter '="/' '="/flower/';
    sub_filter_last_modified on;
    sub_filter_once off;

    # proxy_pass http://unix:/tmp/flower.sock:/;
    proxy_pass http://localhost:5555;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_http_version 1.1;
}


问:
How to link custom field to shortcode?
I'm trying to link a custom field to a custom shortcode so the shortcode shows displays only the posts with the custom field selected to it. </p>

<p>This is my code below for my shortcode as you can see the key is my custom felid "flash_deal". When I enter the shortcode I just get all the perk psots and no the custom field perk posts? </p>

```<code>add_shortcode('foundry_flash', 'shortcode_query_flash');
function shortcode_query_flash($atts, $content){
extract(shortcode_atts(array( // a few default values
   'post_type' => 'perks',
      'posts_per_page' => -1 ,
          'meta_query' => array(
          array(
              'key' => 'flash_deal', // name of custom field
              'value' => '"yes"', // matches exactly "red"
              'compare' => 'LIKE'
              )
          )
), $atts));
</code>```

答:
The code you show is simply setting up variables - not running any queries at all (see extract documentation & shortcode_atts documentation).

I assume you have more code you just didn't add here, so likely the problem is the double quotes around yes that are causing issues. It's literally looking for "quoteyesquote".

As a general working example to get "Parks" Post based on custom meta, you need to use WP_Query as in the docs here.

```<code>$args = array(
    'post_type'  => 'parks',
    'posts_per_page'  => -1,
    'meta_query' => array(
        array(
            'key'     => 'flash_deal',
            'value'   => 'yes',
            'compare' => 'LIKE',
        ),
    ),
);
$query = new WP_Query( $args );
</code>```

Then use a Nested Loop setup to loop through the results.

Title: How to link custom field to shortcode?

Body:
I'm trying to link a custom field to a custom shortcode so the shortcode shows displays only the posts with the custom field selected to it.

This is my code below for my shortcode as you can see the key is my custom felid "flash_deal". When I enter the shortcode I just get all the perk psots and no the custom field perk posts?

add_shortcode('foundry_flash', 'shortcode_query_flash');
function shortcode_query_flash($atts, $content){
extract(shortcode_atts(array( // a few default values
   'post_type' => 'perks',
      'posts_per_page' => -1 ,
          'meta_query' => array(
          array(
              'key' => 'flash_deal', // name of custom field
              'value' => '"yes"', // matches exactly "red"
              'compare' => 'LIKE'
              )
          )
), $atts));

Body:
The code you show is simply setting up variables - not running any queries at all (see extract documentation & shortcode_atts documentation).

I assume you have more code you just didn't add here, so likely the problem is the double quotes around yes that are causing issues. It's literally looking for "quoteyesquote".

As a general working example to get "Parks" Post based on custom meta, you need to use WP_Query as in the docs here.

$args = array(
    'post_type'  => 'parks',
    'posts_per_page'  => -1,
    'meta_query' => array(
        array(
            'key'     => 'flash_deal',
            'value'   => 'yes',
            'compare' => 'LIKE',
        ),
    ),
);
$query = new WP_Query( $args );

Then use a Nested Loop setup to loop through the results.


问:
How report on data in columns by date in SQL (MySQL)
I need to report my data with a column for each date. It's okay if I need to specify the dates ahead of time (i.e., I don't need to discover the dates from the data in the table), but each column has to have the data for just that date.

My source data is normalized, so each row has the data and the date.

For example,

```<code>create table test1 (
id int primary key,
name varchar(32),
created datetime default current_timestamp,
rows int
);
</code>```

So test1 might have date in rows like

```<code>234 fred  2017-01-01  17
235 alice 2017-01-02  32
...
</code>```

I'm looking for output that looks like this:

```<code>NAME       2017-01-01     2017-01-02    2017-01-02
fred           17              19           24
alice          29              32           64
...
</code>```

答:
The way that works (there might be a better way, but this works) is:

```<code>select name
  , max(case when date(created) = '2017-12-01' then rows else 0 end) as '2017-12-01'
  , max(case when date(created) = '2017-12-02' then rows else 0 end) as '2017-12-02'
  , max(case when date(created) = '2017-12-03' then rows else 0 end) as '2017-12-03'
from test1
group by name;
</code>```

The case puts the value of created into the right column by date, else it puts a zero; the max weeds out the zeros so the group by shows the desired values. If you don't else 0, you get NULLS and the NULLS overwhelm the values in the group by and it doesn't work correctly (voice of experience talking).

Body:
I need to report my data with a column for each date. It's okay if I need to specify the dates ahead of time (i.e., I don't need to discover the dates from the data in the table), but each column has to have the data for just that date.

My source data is normalized, so each row has the data and the date.

For example,

create table test1 (
id int primary key,
name varchar(32),
created datetime default current_timestamp,
rows int
);

So test1 might have date in rows like

234 fred  2017-01-01  17
235 alice 2017-01-02  32
...

I'm looking for output that looks like this:

NAME       2017-01-01     2017-01-02    2017-01-02
fred           17              19           24
alice          29              32           64
...

Body:
The way that works (there might be a better way, but this works) is:

select name
  , max(case when date(created) = '2017-12-01' then rows else 0 end) as '2017-12-01'
  , max(case when date(created) = '2017-12-02' then rows else 0 end) as '2017-12-02'
  , max(case when date(created) = '2017-12-03' then rows else 0 end) as '2017-12-03'
from test1
group by name;

The case puts the value of created into the right column by date, else it puts a zero; the max weeds out the zeros so the group by shows the desired values. If you don't else 0, you get NULLS and the NULLS overwhelm the values in the group by and it doesn't work correctly (voice of experience talking).


问:
Analog clock with UIImages for hands?
I want to know how to make an analog clock in iPhone SDK. However, I want the hands of the clock to be custom images and not squares drawn over like in this tutorial:  http://iphone-dev-tips.alterplay.com/2010/03/analog-clock-using-quartz-core.html

The problem with that tutorial is that the clock hands are drawn with Quarzt Core.  I'm okay with that as long as the hands could be custom.  What would be the easiest way to make an Analog Clock this way?

答:
Do it with CALayers. is WAY much easier and performance is better this way.

```<code>CALayer *handLayer = [CALayer layer];
handLayer.contents = (id)[UIImage imageNamed:@"hand.png"].CGImage;
handLayer.anchorPoint = CGPointMake(0.5,0.0)];
[myview.layer addSublayer:handLayer];

//i.e.: if handLayer represents the seconds hand then repeat this every second ;)
handLayer.transform = CGAffineTransformMakeRotation (angle); //set the angle here
</code>```

UPDATE:

I wrote a ClockView sample using CALayers, maybe you find it useful.

Title: Analog clock with UIImages for hands?

Body:
Do it with CALayers. is WAY much easier and performance is better this way.

CALayer *handLayer = [CALayer layer];
handLayer.contents = (id)[UIImage imageNamed:@"hand.png"].CGImage;
handLayer.anchorPoint = CGPointMake(0.5,0.0)];
[myview.layer addSublayer:handLayer];

//i.e.: if handLayer represents the seconds hand then repeat this every second ;)
handLayer.transform = CGAffineTransformMakeRotation (angle); //set the angle here

UPDATE:

I wrote a ClockView sample using CALayers, maybe you find it useful.


问:
Aspose not detecting digits
I cannot for the life of me get aspose to detect any digits, I've tried many different solutions but none seem to work.

Here is an example

As you can see it doesnt look anything remotely right.

I've now got the code (which is on a timer, so that the feed is live):

```<code> private void timer1_Tick(object sender, EventArgs e)
        {

            Image img = Clipboard.GetImage();

            pictureBox1.Image = img;
            ocr.Config.ProcessColoredBackground = true;

            if (img != null)
            {
                var ms = new MemoryStream();

                img.Save(ms, ImageFormat.Bmp); // put here the image format
                ms.Position = 0;

                ocr.Image = ImageStream.FromStream(ms, ImageStreamFormat.Bmp);
                ocr.Config.RemoveNonText = true;
                ocr.Config.Whitelist = new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.' };

                    if (ocr.Process()) // Start processing it
                {
                    toolStripStatusLabel1.Text = "Text: " + ocr.Text;
                }
            }
        }
</code>```

答:
Aspose.OCR APIs support Arial, Times New Roman, Courier New, Tahoma, Calibri and Verdana in Regular, Bold and Italic styles with black text color and white background. At the moment, Aspose.OCR has some issues with colorful backgrounds. Aspose team is working on this feature. You may try Cloud version of Aspose.OCR.

I work with Aspose as Developer evangelist.

Title: Aspose not detecting digits

Body:
I cannot for the life of me get aspose to detect any digits, I've tried many different solutions but none seem to work.

Here is an example

As you can see it doesnt look anything remotely right.

I've now got the code (which is on a timer, so that the feed is live):

 private void timer1_Tick(object sender, EventArgs e)
        {

            Image img = Clipboard.GetImage();

            pictureBox1.Image = img;
            ocr.Config.ProcessColoredBackground = true;

            if (img != null)
            {
                var ms = new MemoryStream();

                img.Save(ms, ImageFormat.Bmp); // put here the image format
                ms.Position = 0;

                ocr.Image = ImageStream.FromStream(ms, ImageStreamFormat.Bmp);
                ocr.Config.RemoveNonText = true;
                ocr.Config.Whitelist = new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.' };

                    if (ocr.Process()) // Start processing it
                {
                    toolStripStatusLabel1.Text = "Text: " + ocr.Text;
                }
            }
        }


问:
Fetching an object of type Set<String> from a JWT?
I am trying to fetch some data from JSON web token, using the JJWT library : https://github.com/jwtk/jjwt

The method signature is like so :

```<code><T> T get(String claimName, Class<T> requiredType);
</code>```

In a claim attribute I have a Set of type String.

When trying to fetch from this method like so

```<code>Claims claims - Jwts.parser()...
claims.get("Role", Set.class);
</code>```

I get the following error

! io.jsonwebtoken.RequiredTypeException: Expected value to be of type:
   interface java.util.Set, but was class java.util.ArrayList

When setting this claim the type is of Set

```<code>public Set<String> getRoles() {
    return roles;
}  ....

claim("Role", user.getRoles())
</code>```

Any ideas how to solve this?

答: JSON and therefore JWT does not have a concept of Set, retrieve the data as an Array / ArrayList and convert it to a Set: Easiest way to convert a List to a Set in Java

Body:
I am trying to fetch some data from JSON web token, using the JJWT library : https://github.com/jwtk/jjwt

The method signature is like so :

<T> T get(String claimName, Class<T> requiredType);

In a claim attribute I have a Set of type String.

When trying to fetch from this method like so

Claims claims - Jwts.parser()...
claims.get("Role", Set.class);

I get the following error

! io.jsonwebtoken.RequiredTypeException: Expected value to be of type:
   interface java.util.Set, but was class java.util.ArrayList

When setting this claim the type is of Set

public Set<String> getRoles() {
    return roles;
}  ....

claim("Role", user.getRoles())

Any ideas how to solve this?


问:
Angularjs nested ng-repeat linking back to object
I have an object like so:

```<code>$scope.group = {
    "Jim Jenkins": {
      "Blue": {
        "Circle": [
          "Item1",
          "Item2",
          "Item3"
        ]
      }
    },
    "Rachel Smith": {
      "Blue": {
        "Circle": [
          "Item 1"
        ]
      },
      "Red": {
        "Circle": [
          "Item 1",
          "Item 2"
        ]
      }
    }
}
</code>```

I created a nested ng-repeat function that cycles through the object and displays it.

```<code><script type="text/ng-template" id="group.html">
    <ul style="padding:10px;">

        <li type="none" ng-repeat="(i, c) in group">

          <div ng-click="test(i)" style="background-color:#fff;padding:5px;" ng-if="i.length > 0">{{ i }}</div>
          <div ng-click="test(c)" style="background-color:#fff;padding:5px;margin-bottom:5px;" ng-if="!i.length">{{ c }}</div>

          <div ng-switch on="i.length > 0">
            <div ng-switch-when="true">
                <div ng-init="group = c;" ng-include="'group.html'"></div>
            </div>
          </div>

        </li>
    </ul>
</script>

<div ng-include="'group.html'" ng-model="group"></div>
</code>```

My only issue is, now I have now way of linking back to the original $scope.group object. I have a ng-click where I display the items and I'd like to be able to know where this element is located (so I know what the parent is, know how many levels in, add more items, etc).

Does anyone know how I can achieve this?

答:
Try like this

var app = angular.module("app", []);

app.controller('mainCtrl', function($scope) {
$scope.isArray = angular.isArray;
  $scope.group = [{
      "Jim Jenkins": {
        "Blue": {
          "Circle": [
            "Item1",
            "Item2",
            "Item3"
          ]
        }
      },
      "Rachel Smith": {
        "Blue": {
          "Circle": [
            "Item 1"
          ]
        },
        "Red": {
          "Circle": [
            "Item 1",
            "Item 2"
          ]
        }
      }

  }]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" />

<div ng-app="app" ng-controller="mainCtrl">
  <script type="text/ng-template" id="dummy.html">
    <ul>
      <li ng-repeat="(k,v) in group">

        <div ng-include=" 'nested.html' " onload="group = v"></div>
      </li>
    </ul>
  </script>
  <script type="text/ng-template" id="nested.html">
    <div ng-repeat="(k1,v1) in v">{{k1}}
      <ul>
       <li ng-if="isArray(v1)" ng-repeat="val in v1">
       {{val}}
       </li>
         </ul>
       <li ng-if="!isArray(v1)" >
        <div ng-include=" 'dummy.html' " onload="group = v1"></div>
       </li>
    </div>
  </script>
  <div ng-include=" 'dummy.html'"></div>
</div></code>```

Body:
I have an object like so:

$scope.group = {
    "Jim Jenkins": {
      "Blue": {
        "Circle": [
          "Item1",
          "Item2",
          "Item3"
        ]
      }
    },
    "Rachel Smith": {
      "Blue": {
        "Circle": [
          "Item 1"
        ]
      },
      "Red": {
        "Circle": [
          "Item 1",
          "Item 2"
        ]
      }
    }
}

I created a nested ng-repeat function that cycles through the object and displays it.

My only issue is, now I have now way of linking back to the original $scope.group object. I have a ng-click where I display the items and I'd like to be able to know where this element is located (so I know what the parent is, know how many levels in, add more items, etc).

Does anyone know how I can achieve this?

Body:
Try like this

var app = angular.module("app", []);

app.controller('mainCtrl', function($scope) {
$scope.isArray = angular.isArray;
  $scope.group = [{
      "Jim Jenkins": {
        "Blue": {
          "Circle": [
            "Item1",
            "Item2",
            "Item3"
          ]
        }
      },
      "Rachel Smith": {
        "Blue": {
          "Circle": [
            "Item 1"
          ]
        },
        "Red": {
          "Circle": [
            "Item 1",
            "Item 2"
          ]
        }
      }

  }]
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" />

<div ng-app="app" ng-controller="mainCtrl">
  <script type="text/ng-template" id="dummy.html">
    <ul>
      <li ng-repeat="(k,v) in group">

        <div ng-include=" 'nested.html' " onload="group = v"></div>
      </li>
    </ul>
  </script>
  <script type="text/ng-template" id="nested.html">
    <div ng-repeat="(k1,v1) in v">{{k1}}
      <ul>
       <li ng-if="isArray(v1)" ng-repeat="val in v1">
       {{val}}
       </li>
         </ul>
       <li ng-if="!isArray(v1)" >
        <div ng-include=" 'dummy.html' " onload="group = v1"></div>
       </li>
    </div>
  </script>
  <div ng-include=" 'dummy.html'"></div>
</div>


问:
Laravel installer v1.4.1 not compatible with PHP 7.1 packages?
I can't install 'laravel 5.5' on fresh 'Pop!_OS' (based on Ubuntu 17.10 by system76) linux instalation.

Can't find how to 'remove symfony/console v4.0.1'.
So can anyone help me solve this annoyance?

I followed https://www.youtube.com/watch?v=b38mUODC1l4 this tutorial and everything went perfect till composer global require "laravel/installer" command.

After entering this command the result in terminal is:

```<code>    Changed current directory to /home/chakra/.config/composer
Using version ^1.4 for laravel/installer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: don't install laravel/installer v1.4.1
    - Conclusion: remove symfony/console v4.0.1
    - Installation request for laravel/installer ^1.4 -> satisfiable by laravel/installer[v1.4.0, v1.4.1].
    - Conclusion: don't install symfony/console v4.0.1
    - laravel/installer v1.4.0 requires symfony/console ~2.3|~3.0 -> satisfiable by symfony/console[v2.3.0, ..., v3.4.1].
    - Can only install one of: symfony/console[v3.0.0, v4.0.1].
    ...
    - Can only install one of: symfony/console[v2.8.9, v4.0.1].
    - Installation request for symfony/console (locked at v4.0.1) -> satisfiable by symfony/console[v4.0.1].

Installation failed, reverting ./composer.json to its original content.
➜  Sites
</code>```

composer.json  /home/chakra/.config/composer (everything is default haven't changed anything like in video tutorial)

After sudo nano composer.json:

```<code>{
    "require": {
        "cpriego/valet-linux": "^2.0"
        }
}
</code>```

Composer, npm, nginx version:

```<code>➜  ~ which composer
/usr/local/bin/composer
➜  ~ composer --version
Composer version 1.5.5 2017-12-01 14:42:57
➜  ~ npm --version
5.5.1
➜  ~ nginx -v
nginx version: nginx/1.12.1 (Ubuntu)
➜  ~
</code>```

答: Have a look at https://stackoverflow.com/a/27754096 to see a list of installed packages - is symfony/console listed with version 4.0.1 there? The Lavarel installer explicitly asks for v2.3 or v3.x of symfony/console so you probably have to remove symfony/console manually first through composer global remove symfony/console

Body:
I can't install 'laravel 5.5' on fresh 'Pop!_OS' (based on Ubuntu 17.10 by system76) linux instalation.

Can't find how to 'remove symfony/console v4.0.1'.
So can anyone help me solve this annoyance?

I followed https://www.youtube.com/watch?v=b38mUODC1l4 this tutorial and everything went perfect till composer global require "laravel/installer" command.

After entering this command the result in terminal is:

    Changed current directory to /home/chakra/.config/composer
Using version ^1.4 for laravel/installer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: don't install laravel/installer v1.4.1
    - Conclusion: remove symfony/console v4.0.1
    - Installation request for laravel/installer ^1.4 -> satisfiable by laravel/installer[v1.4.0, v1.4.1].
    - Conclusion: don't install symfony/console v4.0.1
    - laravel/installer v1.4.0 requires symfony/console ~2.3|~3.0 -> satisfiable by symfony/console[v2.3.0, ..., v3.4.1].
    - Can only install one of: symfony/console[v3.0.0, v4.0.1].
    ...
    - Can only install one of: symfony/console[v2.8.9, v4.0.1].
    - Installation request for symfony/console (locked at v4.0.1) -> satisfiable by symfony/console[v4.0.1].

Installation failed, reverting ./composer.json to its original content.
➜  Sites

composer.json  /home/chakra/.config/composer (everything is default haven't changed anything like in video tutorial)

After sudo nano composer.json:

{
    "require": {
        "cpriego/valet-linux": "^2.0"
        }
}

Composer, npm, nginx version:

➜  ~ which composer
/usr/local/bin/composer
➜  ~ composer --version
Composer version 1.5.5 2017-12-01 14:42:57
➜  ~ npm --version
5.5.1
➜  ~ nginx -v
nginx version: nginx/1.12.1 (Ubuntu)
➜  ~


问:
R LDAvis K=2 createJSON() error
I was using LDAvis package's createJSON() function while my topicmodel was for 2 topics and received this error

```<code>Error in stats::cmdscale(dist.mat, k = 2) : 'k' must be in {1, 2, .. n - 1}
</code>```

Then I tested with reproducible example given here, by putting K=2 and keeping everything same and bumped into this error again in createJSON().

Upon looking at the source code of createJSON() here, the issue is in function jsPCA().
In jsPCA(), while K=2, the dist.mat comes out to be a single value which throws an error in line

```<code>pca.fit <- stats::cmdscale(dist.mat, k = 2)
</code>```

Any advice how to get past this error?

答:
Your problem comes up because of a division by zero issue with the jensenShannon function that sits inside of jsPCA.  The entire jsPCA code looks like this:

```<code> jsPCA <- function(phi){
    jensenShannon <- function(x, y) {
    m <- 0.5 * (x + y)
    0.5 * sum(x * log(x/m)) + 0.5 * sum(y * log(y/m))
    }
    dist.mat <- proxy::dist(x = phi, method = jensenShannon)
    pca.fit <- stats::cmdscale(dist.mat, k = 2)
    data.frame(x = pca.fit[, 1], y = pca.fit[, 2])
    }
</code>```

If m contains zeros, the result is NaN.  The errors trickle through from there.  So, you can prevent the error by specifying a dimensionality-reduction method that tolerates zeros. Indeed, the LDAvis documentation provides an option rooted in t-SNE:

```<code> library("tsne")
 svd_tsne <- function(x) tsne(svd(x)$u)
</code>```

Simply plug this function into mds.method, and you should be good to go:

```<code> createJSON(phi, theta, doc.length, vocab, term.frequency,
            mds.method = svd_tsne,
            plot.opts = list(xlab="", ylab="")
            )
</code>```

Title: R LDAvis K=2 createJSON() error

Body:
I was using LDAvis package's createJSON() function while my topicmodel was for 2 topics and received this error

Error in stats::cmdscale(dist.mat, k = 2) : 'k' must be in {1, 2, .. n - 1}

Then I tested with reproducible example given here, by putting K=2 and keeping everything same and bumped into this error again in createJSON().

Upon looking at the source code of createJSON() here, the issue is in function jsPCA().
In jsPCA(), while K=2, the dist.mat comes out to be a single value which throws an error in line

pca.fit <- stats::cmdscale(dist.mat, k = 2)

Any advice how to get past this error?

Body:
Your problem comes up because of a division by zero issue with the jensenShannon function that sits inside of jsPCA.  The entire jsPCA code looks like this:

 jsPCA <- function(phi){
    jensenShannon <- function(x, y) {
    m <- 0.5 * (x + y)
    0.5 * sum(x * log(x/m)) + 0.5 * sum(y * log(y/m))
    }
    dist.mat <- proxy::dist(x = phi, method = jensenShannon)
    pca.fit <- stats::cmdscale(dist.mat, k = 2)
    data.frame(x = pca.fit[, 1], y = pca.fit[, 2])
    }

If m contains zeros, the result is NaN.  The errors trickle through from there.  So, you can prevent the error by specifying a dimensionality-reduction method that tolerates zeros. Indeed, the LDAvis documentation provides an option rooted in t-SNE:

 library("tsne")
 svd_tsne <- function(x) tsne(svd(x)$u)

Simply plug this function into mds.method, and you should be good to go:

 createJSON(phi, theta, doc.length, vocab, term.frequency,
            mds.method = svd_tsne,
            plot.opts = list(xlab="", ylab="")
            )


问:
AUTO Sign in to facebook iphone
I am developing an app for iphone which needs to read all the information from a particular group for which I am a member. Is it possible to auto sign and get access token and access the group information on Facebook and display to user. I don't mind saving  my login credentials in code. I want users to get a smooth experience with no hassles of logging in.

Is this possible ..??? How ?

THanks in advance...

答: you can try [_session resume] using this if once user logged in then app won't ask again for login until you forcefully logout the user using [_session logout]. For more info download facebook ios sdk from github and try to read the sample app.</p>

Title: AUTO Sign in to facebook iphone


问:
Hide a specific product in Woocommerce product widget
In WooCommerce, I am trying hide a specific product in the Woocommerce product widget.

I found a solution to exclude it via category:

```<code>function exclude_widget_categories($args){
    $exclude = "11,10,8,7,9"; // IDs of excluded product categories
    $args["exclude"] = $exclude;
    return $args;
}
add_filter("widget_categories_args","exclude_widget_categories");
</code>```

But thats not what I want. I need it for a specific product with the id 2386.

How to hide a specific product in woocommerce product widget?

答:
Using a custom function hooked in woocommerce_products_widget_query_args filter hook this way:

```<code>add_filter('woocommerce_products_widget_query_args', 'exclude_product_from_widget', 10, 1 );
function exclude_product_from_widget( $query_args ){
    // HERE define your product IDs to exclude in the array
    $product_ids = array(2386);

    $query_args['post__not_in'] = $product_ids;
    return $query_args;
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works

Body:
In WooCommerce, I am trying hide a specific product in the Woocommerce product widget.

I found a solution to exclude it via category:

function exclude_widget_categories($args){
    $exclude = "11,10,8,7,9"; // IDs of excluded product categories
    $args["exclude"] = $exclude;
    return $args;
}
add_filter("widget_categories_args","exclude_widget_categories");

But thats not what I want. I need it for a specific product with the id 2386.

How to hide a specific product in woocommerce product widget?

Body:
Using a custom function hooked in woocommerce_products_widget_query_args filter hook this way:

add_filter('woocommerce_products_widget_query_args', 'exclude_product_from_widget', 10, 1 );
function exclude_product_from_widget( $query_args ){
    // HERE define your product IDs to exclude in the array
    $product_ids = array(2386);

    $query_args['post__not_in'] = $product_ids;
    return $query_args;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works