问:
make vertical moving background
I'm beginner in Spritekit and I try to make background move vertically

I did know how
this what in the controller

```<code>class GameViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let scene = GameScene(size: view.bounds.size)
        let skView = view as! SKView
        skView.showsFPS = true
        skView.showsNodeCount = true
        skView.ignoresSiblingOrder = true
        scene.scaleMode = .resizeFill
        skView.presentScene(scene)
    }
</code>```

and this the scene

```<code>class GameScene: SKScene {

var background = SKSpriteNode()
override func didMove(to view: SKView) {

    let backgroundTexture = SKTexture(imageNamed: "bbbgg.png")

    let shiftBackground = SKAction.moveBy(x: 0, y: -backgroundTexture.size().height, duration: 5)
    let replaceBackground = SKAction.moveBy(x: 0, y:backgroundTexture.size().height, duration: 0)
    let movingAndReplacingBackground = SKAction.repeatForever(SKAction.sequence([shiftBackground,replaceBackground]))

    for i in 1...3{
        background=SKSpriteNode(texture:backgroundTexture)
        background.position = CGPoint(x: 0, y: 0)
        background.size.height = self.frame.height
        background.run(movingAndReplacingBackground)

        self.addChild(background)
    }
}
</code>```

}

the problem is the background move horizontally and after it arrives to the end of screen disappear, then begins move from the beginning of the screen again

I want it work vertically without disappearing

答:
The background move horizontally because declarations of moveBy (shiftBackground, replaceBackground) works on the x axe (horizontally). You need to work on the y axe (vertically).

```<code>    let shiftBackground = SKAction.moveBy(x: 0, y: -backgroundTexture.size().height, duration: 5)
    let replaceBackground = SKAction.moveBy(x: 0, y: backgroundTexture.size().height, duration: 0)
</code>```

At the first line, the background move from it position to it position - it height. At the second line, it return to it first position (I think moveBy is relative).

_

The background move again because you use the function SKAction.repeatForever (movingAndReplacingBackground). I think you can remove it.

```<code>    let movingAndReplacingBackground = SKAction.sequence([shiftBackground,replaceBackground])
</code>```

Edit :

I forget the loop.

In the loop, you give to the background an initial position.

```<code>            background.position = CGPoint(x: backgroundTexture.size().width/2 + (backgroundTexture.size().width * CGFloat(i)), y: self.frame.midY)
</code>```

Try to replace it by 0, middle if you want an immediately visible background

```<code>        background.position = CGPoint(x: 0, y: self.frame.midY)
</code>```

Or -height, 0 if you want the background appear by the top of the screen. In this case you need to replace shiftBackground and replaceBackground

```<code>        background.position = CGPoint(x: -backgroundTexture.size().height, y: 0)

    and

    let shiftBackground = SKAction.moveBy(x: 0, y: backgroundTexture.size().height, duration: 5)

    let replaceBackground = SKAction.moveBy(x: 0, y: 0, duration: 0)
</code>```

I'm not sure, but I think, if you want only one mouvement, you can remove th sequence :

```<code>class GameScene: SKScene {

    var background = SKSpriteNode()
    override func didMove(to view: SKView) {

        let backgroundTexture = SKTexture(imageNamed: "bbbgg.png")

        let scrollByTopBackground = SKAction.moveBy(x: O, y: backgroundTexture.size().height, duration: 5)

        background = SKSpriteNode(texture:backgroundTexture)
        background.position = CGPoint(x: -backgroundTexture.size().height, y: self.frame.midY)
        background.size.height = self.frame.height
        background.run(scrollByTopBackground)

        self.addChild(background)
    }
}
</code>```

Edit to answer you, try this...

```<code>class GameScene: SKScene {

var background = SKSpriteNode()
override func didMove(to view: SKView) {

    let backgroundTexture = SKTexture(imageNamed: "bbbgg.png")

    let shiftBackground = SKAction.moveBy(x: 0, y: -backgroundTexture.size().height, duration: 5)
    let replaceBackground = SKAction.moveBy(x: 0, y:backgroundTexture.size().height, duration: 0)
    let movingAndReplacingBackground = SKAction.repeatForever(SKAction.sequence([shiftBackground,replaceBackground]))

    for i in 0...2 {
        background=SKSpriteNode(texture:backgroundTexture)
        background.position = CGPoint(x: 0, y: self.frame.midY + (backgroundTexture.size().height * CGFloat(i)))
        background.size.height = self.frame.height
        background.run(movingAndReplacingBackground)

        self.addChild(background)
    }
}
</code>```

Title: make vertical moving background

Body:
I'm beginner in Spritekit and I try to make background move vertically

I did know how
this what in the controller

class GameViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let scene = GameScene(size: view.bounds.size)
        let skView = view as! SKView
        skView.showsFPS = true
        skView.showsNodeCount = true
        skView.ignoresSiblingOrder = true
        scene.scaleMode = .resizeFill
        skView.presentScene(scene)
    }

and this the scene

class GameScene: SKScene {

var background = SKSpriteNode()
override func didMove(to view: SKView) {

    let backgroundTexture = SKTexture(imageNamed: "bbbgg.png")

    let shiftBackground = SKAction.moveBy(x: 0, y: -backgroundTexture.size().height, duration: 5)
    let replaceBackground = SKAction.moveBy(x: 0, y:backgroundTexture.size().height, duration: 0)
    let movingAndReplacingBackground = SKAction.repeatForever(SKAction.sequence([shiftBackground,replaceBackground]))

    for i in 1...3{
        background=SKSpriteNode(texture:backgroundTexture)
        background.position = CGPoint(x: 0, y: 0)
        background.size.height = self.frame.height
        background.run(movingAndReplacingBackground)

        self.addChild(background)
    }
}

}

the problem is the background move horizontally and after it arrives to the end of screen disappear, then begins move from the beginning of the screen again

I want it work vertically without disappearing

Body:
The background move horizontally because declarations of moveBy (shiftBackground, replaceBackground) works on the x axe (horizontally). You need to work on the y axe (vertically).

    let shiftBackground = SKAction.moveBy(x: 0, y: -backgroundTexture.size().height, duration: 5)
    let replaceBackground = SKAction.moveBy(x: 0, y: backgroundTexture.size().height, duration: 0)

At the first line, the background move from it position to it position - it height. At the second line, it return to it first position (I think moveBy is relative).

_

The background move again because you use the function SKAction.repeatForever (movingAndReplacingBackground). I think you can remove it.

    let movingAndReplacingBackground = SKAction.sequence([shiftBackground,replaceBackground])

Edit :

I forget the loop.

In the loop, you give to the background an initial position.

            background.position = CGPoint(x: backgroundTexture.size().width/2 + (backgroundTexture.size().width * CGFloat(i)), y: self.frame.midY)

Try to replace it by 0, middle if you want an immediately visible background

        background.position = CGPoint(x: 0, y: self.frame.midY)

Or -height, 0 if you want the background appear by the top of the screen. In this case you need to replace shiftBackground and replaceBackground

        background.position = CGPoint(x: -backgroundTexture.size().height, y: 0)

    and

    let shiftBackground = SKAction.moveBy(x: 0, y: backgroundTexture.size().height, duration: 5)

    let replaceBackground = SKAction.moveBy(x: 0, y: 0, duration: 0)

I'm not sure, but I think, if you want only one mouvement, you can remove th sequence :

class GameScene: SKScene {

    var background = SKSpriteNode()
    override func didMove(to view: SKView) {

        let backgroundTexture = SKTexture(imageNamed: "bbbgg.png")

        let scrollByTopBackground = SKAction.moveBy(x: O, y: backgroundTexture.size().height, duration: 5)

        background = SKSpriteNode(texture:backgroundTexture)
        background.position = CGPoint(x: -backgroundTexture.size().height, y: self.frame.midY)
        background.size.height = self.frame.height
        background.run(scrollByTopBackground)

        self.addChild(background)
    }
}

Edit to answer you, try this...

class GameScene: SKScene {

var background = SKSpriteNode()
override func didMove(to view: SKView) {

    let backgroundTexture = SKTexture(imageNamed: "bbbgg.png")

    let shiftBackground = SKAction.moveBy(x: 0, y: -backgroundTexture.size().height, duration: 5)
    let replaceBackground = SKAction.moveBy(x: 0, y:backgroundTexture.size().height, duration: 0)
    let movingAndReplacingBackground = SKAction.repeatForever(SKAction.sequence([shiftBackground,replaceBackground]))

    for i in 0...2 {
        background=SKSpriteNode(texture:backgroundTexture)
        background.position = CGPoint(x: 0, y: self.frame.midY + (backgroundTexture.size().height * CGFloat(i)))
        background.size.height = self.frame.height
        background.run(movingAndReplacingBackground)

        self.addChild(background)
    }
}


来源: stackexchange

问:
Porting a Visual C++ project to C#
I got my hands on some well documented C++ code that's about 1KLOC. It would take me a significant amount of time to port this line by line and debug the results, so I'm wondering if there are tools or ways to do it faster, and I have questions in case I have to do it fully manually.

Specific questions:

Does C# also support overriding operators like * and +?

What to do with the C++ memory management code like alloc() and free()?

How to identify functions used from <stdio.h>, <conio.h> and <math.h>?

How to find replacements to such system functions?

Does C# have any special/open source libraries that provide such functions?

No graphics libraries have been used, its purely command line based.

答:
1 - C# also support operator overloading see : http://msdn.microsoft.com/en-us/library/aa288467(VS.71).aspx (it looks very much to c++ operator overriding)

2 - C# is garbage collected so you only need "new" instead of alloc. free is done by the garbage collector

3 - I have no idea , but when porting code you would have to find in standard c# library the equivalents

4 - In MSDN there is a lot of information.

5 - ( http://code2code.net/ ) ??? but better to do it at hand

More information on coding standards : http://msdn.microsoft.com/en-us/library/xzf533w0.aspx
ie naming: http://msdn.microsoft.com/en-us/library/x2dbyw72.aspx

ContentLicense: CC BY-SA 2.5

Title: Porting a Visual C++ project to C#


问:
Remove .php from Url using Plesk Directives
i'm using plesk onyx and nginx
Is there anyway to remove the .php from my links using directives ?
here is what i have so far but i still have .php at the end of url</p>

```<code>    #ignored: condition 0
if ($http_host ~* "^www\."){
    set $rule_0 1;
    break;
}
if ($rule_0 = "1"){
    rewrite ^/ https://example.com$uri permanent;
}
rewrite ^/directory/([A-Za-z-]+)/?$ https://example.com/directory/$1.php last;
rewrite ^/rss/medicinecategory.php$ https://example.com/directory/medical-specialties permanent;
rewrite ^/rss/medicalconditions.php$ https://example.com/directory/medical-conditions permanent;
rewrite ^/rss/cancers.php$ https://example.com/directory/cancers permanent;
rewrite ^/rss/infectiousdiseases.php$ https://example.com/directory/infectious-diseases permanent;
rewrite ^/rss/surgical_procedures.php$ https://example.com/directory/medical-procedures permanent;
rewrite ^/rss/therapies.php$ https://example.com/directory/therapies permanent;
rewrite ^/rss/vaccines.php$ https://example.com/directory/vaccines permanent;
rewrite ^/rss/drugs.php$ https://example.com/directory/drugs permanent;
rewrite ^/rss/health_management.php$ https://example.com/directory/health-management permanent;
rewrite ^/rss/medical_education.php$ https://example.com/directory/medical-training permanent;
if ($args ~ "podcasts|blogs|news"){
    set $rule_12 1$rule_12;
}
if ($rule_12 = "1"){
    rewrite ^/rss/index.php/Consumer-Health-Advice/91/$ https://example.com/rss/index.php/Consumer-Health-News/26/ permanent;
}
rewrite ^/rss/index.php/Consumer-Health-Advice/91/$ https://example.com/rss/index.php/Consumer-Health-News/26/$1? permanent;
</code>```

答:
A similar issue was discussed on How to remove both .php and .html extensions from url using NGINX?.

This answer looks useful: https://stackoverflow.com/a/21915845/4508593

ContentLicense: CC BY-SA 3.0

Body:
i'm using plesk onyx and nginx
Is there anyway to remove the .php from my links using directives ?
here is what i have so far but i still have .php at the end of url

    #ignored: condition 0
if ($http_host ~* "^www\."){
    set $rule_0 1;
    break;
}
if ($rule_0 = "1"){
    rewrite ^/ https://example.com$uri permanent;
}
rewrite ^/directory/([A-Za-z-]+)/?$ https://example.com/directory/$1.php last;
rewrite ^/rss/medicinecategory.php$ https://example.com/directory/medical-specialties permanent;
rewrite ^/rss/medicalconditions.php$ https://example.com/directory/medical-conditions permanent;
rewrite ^/rss/cancers.php$ https://example.com/directory/cancers permanent;
rewrite ^/rss/infectiousdiseases.php$ https://example.com/directory/infectious-diseases permanent;
rewrite ^/rss/surgical_procedures.php$ https://example.com/directory/medical-procedures permanent;
rewrite ^/rss/therapies.php$ https://example.com/directory/therapies permanent;
rewrite ^/rss/vaccines.php$ https://example.com/directory/vaccines permanent;
rewrite ^/rss/drugs.php$ https://example.com/directory/drugs permanent;
rewrite ^/rss/health_management.php$ https://example.com/directory/health-management permanent;
rewrite ^/rss/medical_education.php$ https://example.com/directory/medical-training permanent;
if ($args ~ "podcasts|blogs|news"){
    set $rule_12 1$rule_12;
}
if ($rule_12 = "1"){
    rewrite ^/rss/index.php/Consumer-Health-Advice/91/$ https://example.com/rss/index.php/Consumer-Health-News/26/ permanent;
}
rewrite ^/rss/index.php/Consumer-Health-Advice/91/$ https://example.com/rss/index.php/Consumer-Health-News/26/$1? permanent;


问:
Functional way to take element in a list until a limit in Scala
The aim of the method is to take elements in a list until a limit is reached.

e.g.

I've come up with 2 different implementations

```<code>def take(l: List[Int], limit: Int): List[Int] = {
  var sum = 0
  l.takeWhile { e =>
    sum += e
    sum <= limit
  }
}
</code>```

It is straightforward, but a mutable state is used.

```<code>def take(l: List[Int], limit: Int): List[Int] = {
  val summed = l.toStream.scanLeft(0) { case (e, sum) => sum + e }
  l.take(summed.indexWhere(_ > limit) - 1)
}
</code>```

It seems cleaner, but it's more verbose and perhaps less memory efficient because a stream is needed.

Is there a better way ?

答:
You could also do that in a single pass with a fold:

```<code>  def take(l: List[Int], limit: Int): List[Int] =
    l.fold((List.empty[Int], 0)) { case ((res, acc), next) =>
      if (acc + next > limit)
        (res, limit)
      else
        (next :: res, next + acc)
    }
</code>```

Because the standard lists aren't lazy, and neither is fold, this will always traverse the entire list. One alternative would be to use cats' iteratorFoldM instead for an implementation that short circuits once the limit is reached.

You could also write the short circuiting fold directly using tail recursion, something along those lines:

```<code>def take(l: List[Int], limit: Int): List[Int] = {
  @annotation.tailrec
  def take0(list: List[Int], accList: List[Int], accSum: Int) : List[Int] =
    list match {
      case h :: t if accSum + h < limit =>
        take0(t, h :: accList, h + accSum)
      case _ => accList
    }
  take0(l, Nil, 0).reverse
}
</code>```

Note that this second solution might be faster, but also less elegant as it requires additional effort to prove that the implementation terminates, something obvious when using a fold.

Body:
The aim of the method is to take elements in a list until a limit is reached.

e.g.

I've come up with 2 different implementations

def take(l: List[Int], limit: Int): List[Int] = {
  var sum = 0
  l.takeWhile { e =>
    sum += e
    sum <= limit
  }
}

It is straightforward, but a mutable state is used.

def take(l: List[Int], limit: Int): List[Int] = {
  val summed = l.toStream.scanLeft(0) { case (e, sum) => sum + e }
  l.take(summed.indexWhere(_ > limit) - 1)
}

It seems cleaner, but it's more verbose and perhaps less memory efficient because a stream is needed.

Is there a better way ?

Body:
You could also do that in a single pass with a fold:

  def take(l: List[Int], limit: Int): List[Int] =
    l.fold((List.empty[Int], 0)) { case ((res, acc), next) =>
      if (acc + next > limit)
        (res, limit)
      else
        (next :: res, next + acc)
    }

Because the standard lists aren't lazy, and neither is fold, this will always traverse the entire list. One alternative would be to use cats' iteratorFoldM instead for an implementation that short circuits once the limit is reached.

You could also write the short circuiting fold directly using tail recursion, something along those lines:

def take(l: List[Int], limit: Int): List[Int] = {
  @annotation.tailrec
  def take0(list: List[Int], accList: List[Int], accSum: Int) : List[Int] =
    list match {
      case h :: t if accSum + h < limit =>
        take0(t, h :: accList, h + accSum)
      case _ => accList
    }
  take0(l, Nil, 0).reverse
}

Note that this second solution might be faster, but also less elegant as it requires additional effort to prove that the implementation terminates, something obvious when using a fold.


问:
select data from couple of subqueries in mysql
I have problem with mysql
I need to select sums from some joined tables but I dont get the result I need.
here's my query.

```<code>SELECT kelas.kelas as kelas, perpus.perpus as perpus
    FROM
    (SELECT b.id_alt, SUM(a.nilai_crips) AS kelas FROM crips AS a JOIN list AS b ON a.id_crips=b.id_crips where a.id_kriteria=34 group by b.id_alt
    )as Kelas,
    (SELECT SUM(a.nilai_crips) AS perpus FROM crips AS a JOIN list AS b ON a.id_crips=b.id_crips where a.id_kriteria=35 group by b.id_alt
    )as perpus
    group by kelas.id_alt
</code>```

the 1st column shows the right result but the second column doesn't.

```<code>kelas | perpus
100   | 100
100   | 100
100   | 100
100   | 100
10    | 100
100   | 100
80    | 100
100   | 100
</code>```

if I deleted the 1st subquery, the the column would return the right result.

```<code>perpus
100
100
100
100
100
100
100
76
</code>```

what is wrong with my query? thank you in advance for the help.

答:
Use a single SELECT, and conditionally add the values:</p>

```<code>SELECT
    b.id_alt,
    SUM(IF(a.id_kriteria = 34,a.nilai_crips,0)) AS kelas,
    SUM(IF(a.id_kriteria = 35,a.nilai_crips,0)) AS perpus
FROM crips AS a
JOIN list AS b
ON a.id_crips = b.id_crips
WHERE a.id_kriteria IN (34,35)
GROUP BY b.id_alt;
</code>```

Body:
I have problem with mysql
I need to select sums from some joined tables but I dont get the result I need.
here's my query.

SELECT kelas.kelas as kelas, perpus.perpus as perpus
    FROM
    (SELECT b.id_alt, SUM(a.nilai_crips) AS kelas FROM crips AS a JOIN list AS b ON a.id_crips=b.id_crips where a.id_kriteria=34 group by b.id_alt
    )as Kelas,
    (SELECT SUM(a.nilai_crips) AS perpus FROM crips AS a JOIN list AS b ON a.id_crips=b.id_crips where a.id_kriteria=35 group by b.id_alt
    )as perpus
    group by kelas.id_alt

the 1st column shows the right result but the second column doesn't.

kelas | perpus
100   | 100
100   | 100
100   | 100
100   | 100
10    | 100
100   | 100
80    | 100
100   | 100

if I deleted the 1st subquery, the the column would return the right result.

perpus
100
100
100
100
100
100
100
76

what is wrong with my query? thank you in advance for the help.

Body:
Use a single SELECT, and conditionally add the values:

SELECT
    b.id_alt,
    SUM(IF(a.id_kriteria = 34,a.nilai_crips,0)) AS kelas,
    SUM(IF(a.id_kriteria = 35,a.nilai_crips,0)) AS perpus
FROM crips AS a
JOIN list AS b
ON a.id_crips = b.id_crips
WHERE a.id_kriteria IN (34,35)
GROUP BY b.id_alt;


问:
How to pass byte data from C# to Servlet in Java
I am trying to pass byte data from C# to java servlet . The code is as follows :

```<code>byte[] data = futronicApp.getFingerVerificationData(name,SampleModel);
String passingData = "cust_no=" + name + "&serial=" + serial + "&temp=" + data;
jsonparser = new JSONParser("http://10.11.201.31:8085/FingerEnrollVerify/EnrolledFingerVerify", "POST", passingData );
</code>```

The definition of JSONParser class is as follows :

```<code>public JSONParser(string url)
        {
            // Create a request using a URL that can receive a post.
            request = WebRequest.Create(url);
        }
        public JSONParser(string url, string method) : this(url)
        {
            if (method.Equals("GET") || method.Equals("POST"))
            {
                // Set the Method property of the request to POST.
                request.Method = method;
            }
            else
            {
                throw new Exception("Invalid Method Type");
            }
        }
        public JSONParser(string url, string method, string data) : this(url, method)
        {
            // Create POST data and convert it to a byte array.
            string postData = data;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            // Get the request stream.
            dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close();
        }
</code>```

Then in java servlet I am trying to get this byte data . The code is as follows :

```<code>protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("Finger Enroll Verify");

        String customerNumber = request.getParameter("cust_no");
        System.out.println("cust_no is "+customerNumber);

        String serial = request.getParameter("serial");
        int serial_no = Integer.parseInt(serial);
        System.out.println("Serial_no is "+serial_no);

        InputStream inputStream = request.getInputStream();
        byte[] fingerbytes = IOUtils.toByteArray(inputStream);
        System.out.println("fingerbytes length: "+fingerbytes.length);
}
</code>```

But I am getting "fingerbytes length: 0" . Why ? How can I pass byte data from C# to Java servlet ? Please help me .

答:
bytes cannot be treated like chars like this.
Effectively the reason this doesn't work is because you have a string with different types of data in it.

Normally you would "stream" bytes to a server rather than "stringify" them as the string representation of a byte is usually a number.

luckily though there is a built in function to allow this ...

```<code>String passingData = "cust_no=" + name + "&serial=" + serial + "&temp=" + System.Text.Encoding.Default.GetString(data);
</code>```

this will get you your whole post as a string,

then on the java end you will have to split the string from the byte array and to the same in reverse by using somehting like ....

```<code>var dataString = postedString.split("&temp=")[1];
var data = dataString.getBytes();
</code>```

Body:
I am trying to pass byte data from C# to java servlet . The code is as follows :

byte[] data = futronicApp.getFingerVerificationData(name,SampleModel);
String passingData = "cust_no=" + name + "&serial=" + serial + "&temp=" + data;
jsonparser = new JSONParser("http://10.11.201.31:8085/FingerEnrollVerify/EnrolledFingerVerify", "POST", passingData );

The definition of JSONParser class is as follows :

public JSONParser(string url)
        {
            // Create a request using a URL that can receive a post.
            request = WebRequest.Create(url);
        }
        public JSONParser(string url, string method) : this(url)
        {
            if (method.Equals("GET") || method.Equals("POST"))
            {
                // Set the Method property of the request to POST.
                request.Method = method;
            }
            else
            {
                throw new Exception("Invalid Method Type");
            }
        }
        public JSONParser(string url, string method, string data) : this(url, method)
        {
            // Create POST data and convert it to a byte array.
            string postData = data;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            // Get the request stream.
            dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close();
        }

Then in java servlet I am trying to get this byte data . The code is as follows :

protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("Finger Enroll Verify");

        String customerNumber = request.getParameter("cust_no");
        System.out.println("cust_no is "+customerNumber);

        String serial = request.getParameter("serial");
        int serial_no = Integer.parseInt(serial);
        System.out.println("Serial_no is "+serial_no);

        InputStream inputStream = request.getInputStream();
        byte[] fingerbytes = IOUtils.toByteArray(inputStream);
        System.out.println("fingerbytes length: "+fingerbytes.length);
}

But I am getting "fingerbytes length: 0" . Why ? How can I pass byte data from C# to Java servlet ? Please help me .

Body:
bytes cannot be treated like chars like this.
Effectively the reason this doesn't work is because you have a string with different types of data in it.

Normally you would "stream" bytes to a server rather than "stringify" them as the string representation of a byte is usually a number.

luckily though there is a built in function to allow this ...

String passingData = "cust_no=" + name + "&serial=" + serial + "&temp=" + System.Text.Encoding.Default.GetString(data);

this will get you your whole post as a string,

then on the java end you will have to split the string from the byte array and to the same in reverse by using somehting like ....

var dataString = postedString.split("&temp=")[1];
var data = dataString.getBytes();


问:
Why I am not read xml file using FileSystemResource class
Problem:

I have created a program that will read my applicationContext.xml file from the specified path using FilesystemResource and call B.Method.
I am unable to understood why I am getting error like this:

Can anyone guide me how to solve this problem:

Below is the Code

```<code>public static void main(String[] args) {
    Resource res=null;
    BeanFactory factory=null;
    Object obj=null;
    WishMessageGenerator generator=null;
    //Locate Cfg File
    res=new FileSystemResource("com/jc/cfgs/applicationContext.xml");
    //Create IOC Container
    factory=new XmlBeanFactory(res);
    //getBean Class Object
    obj=factory.getBean("wish");
    //TypeCasting
    generator=(WishMessageGenerator)obj;
    //Invoke Businees Method
    System.out.println("Message ="+generator.wishMsg("jalaj"));

}

}
</code>```

Error Shown :

```<code>Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from file [/Users/mansi/Desktop/springapp/SpringApp4/com/jc/cfgs/applicationContext.xml]; nested exception is java.io.FileNotFoundException: com/jc/cfgs/applicationContext.xml (No such file or directory)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:79)
at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:67)
at com.jc.test.Test.main(Test.java:20)
Caused by: java.io.FileNotFoundException: com/jc/cfgs/applicationContext.xml (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at org.springframework.core.io.FileSystemResource.getInputStream(FileSystemResource.java:115)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
... 4 more
</code>```

DirectoryStructure

答:
If the resource is in the classpath, you should not use FileSystemResource that is designed to specify a absolute path.

ClassPathResource that is also  a org.springframework.core.io.Resource implementation is more suitable.

In your actual code, the src folder is in the classpath, so this should be fine :

```<code>res = new ClassPathResource("com/jc/cfgs/applicationContext.xml");
</code>```

Body:
Problem:

I have created a program that will read my applicationContext.xml file from the specified path using FilesystemResource and call B.Method.
I am unable to understood why I am getting error like this:

Can anyone guide me how to solve this problem:

Below is the Code

public static void main(String[] args) {
    Resource res=null;
    BeanFactory factory=null;
    Object obj=null;
    WishMessageGenerator generator=null;
    //Locate Cfg File
    res=new FileSystemResource("com/jc/cfgs/applicationContext.xml");
    //Create IOC Container
    factory=new XmlBeanFactory(res);
    //getBean Class Object
    obj=factory.getBean("wish");
    //TypeCasting
    generator=(WishMessageGenerator)obj;
    //Invoke Businees Method
    System.out.println("Message ="+generator.wishMsg("jalaj"));

}

}

Error Shown :

Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from file [/Users/mansi/Desktop/springapp/SpringApp4/com/jc/cfgs/applicationContext.xml]; nested exception is java.io.FileNotFoundException: com/jc/cfgs/applicationContext.xml (No such file or directory)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:79)
at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:67)
at com.jc.test.Test.main(Test.java:20)
Caused by: java.io.FileNotFoundException: com/jc/cfgs/applicationContext.xml (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at org.springframework.core.io.FileSystemResource.getInputStream(FileSystemResource.java:115)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
... 4 more

DirectoryStructure

Body:
If the resource is in the classpath, you should not use FileSystemResource that is designed to specify a absolute path.

ClassPathResource that is also  a org.springframework.core.io.Resource implementation is more suitable.

In your actual code, the src folder is in the classpath, so this should be fine :

res = new ClassPathResource("com/jc/cfgs/applicationContext.xml");

ContentLicense: CC BY-SA 4.0


问:
what should i do next for creating my game bot in telegram?
I have made a bot in telegram.

next used the /newgame command to make new game.

the botfather made it and now I get this message:

"You can now use Example as the short_name parameter value in Bot API. Your game link is t.me/NanoNewsBot?game=Example. Open it to start developing the game!"

what should I do next?
I clicked on it and it opens the forward window. I forward it to my bot and nothing happens.

答:
I answered this question in this question:
Telegram Bot Game not working

An example in PHP:

```<code>if(isset($update["callback_query"])) {
    $parameters["method"] = "answerCallbackQuery";
    $parameters["callback_query_id"] = $update["callback_query"]["id"];
    $parameters["url"] = "<url-game>";
    echo json_encode($parameters);
    die;
}
</code>```

Body:
I answered this question in this question:
Telegram Bot Game not working

An example in PHP:

if(isset($update["callback_query"])) {
    $parameters["method"] = "answerCallbackQuery";
    $parameters["callback_query_id"] = $update["callback_query"]["id"];
    $parameters["url"] = "<url-game>";
    echo json_encode($parameters);
    die;
}


问:
Filtering Choice field in django model Form based on F.K relation
Here is my sample model in model.py:

class Division(models.Model):
    title = models.CharField(max_length=10, unique=True)
    ......
class Place(models.Model):
    name = models.CharField(max_length=50, unique=True)
    division = models.ForeignKey(Division, related_name='places')
    .....
class Story(models.Model):
    story_division = models.ForeignKey(Division)
    story_page = models.ForeignKey(Place)
    ......```
</div>
</div>
</p>

<p>And in my forms.py :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class storyForm(forms.ModelForm):
    class Meta:
        model = Story
        fields = ('story_division','story_page'...)
        ......</code>```

Now my storyForm shows two choice field, Division and Place, what i want is to dynamically filter from the dropdown list where places are related to its above division choice. How do i do that ?

答:
I don't think that django offers this out of the box. Didn't try Django select2 but I normally do this sort of thing with an ajax call.

So for your example: Every time the story_division change, you should call a view that will populate the story_page combo.

Body:
Here is my sample model in model.py:

class Division(models.Model):
    title = models.CharField(max_length=10, unique=True)
    ......
class Place(models.Model):
    name = models.CharField(max_length=50, unique=True)
    division = models.ForeignKey(Division, related_name='places')
    .....
class Story(models.Model):
    story_division = models.ForeignKey(Division)
    story_page = models.ForeignKey(Place)
    ......

And in my forms.py :

class storyForm(forms.ModelForm):
    class Meta:
        model = Story
        fields = ('story_division','story_page'...)
        ......

Now my storyForm shows two choice field, Division and Place, what i want is to dynamically filter from the dropdown list where places are related to its above division choice. How do i do that ?


问:
Randomize order of a MongoDB query in Go
Here is my query :

```<code>c := session.DB("searchV").C("video")
var results []BadVideo
err5 := c.Find(nil).All(&results)
fmt.Println("request done")
if err5 != nil {
    panic(err5)
}
var i = 0
for _,badvideo := range results {
}
</code>```

I would like to randomize the order of browsing the items of the query for making operation on each item of the request ...

So each time I run it, I browse it in a different order.

答:
Manual shuffling

Here's a simple shuffle algorithm, which shuffles (randomizes) a []BadVido slice:

```<code>func shuffle(r []BadVideo) {
    for i := len(r) - 1; i > 0; i-- {
        j := rand.Intn(i + 1)
        r[i], r[j] = r[j], r[i]
    }
}
</code>```

So after you loaded your results, simply call shuffle(results) on it.

For testing, I will use a simple BadVideo type:

```<code>type BadVideo struct {
    Name string
}

func main() {
    rand.Seed(time.Now().UnixNano())
    results := []BadVideo{{"a"}, {"b"}, {"c"}, {"d"}, {"e"}}
    shuffle(results)
    fmt.Println(results)
}
</code>```

Output (try it on the Go Playground):

```<code>[{c} {d} {b} {e} {a}]
</code>```

How it works:

To shuffle a slice, the shuffle() function randomly selects one element from the slice for each index. It does it like iterating over all elements downward, and selects a random element from the remaining slice (including index of the element we're currently selecting, because random orders also include ones where an element "stays in place"), and using a random index to swaps the element with the chosen random one. The loop goes until i > 0 (and not until i >=0), because if only 1 element left, no need to swap it with itself.

Using rand.Perm()

Another variant of shuffle() could take advantage of rand.Perm() which returns a slice containing shuffled numbers. We can use these random numbers to tell how to reorder the results:

```<code>func shuffle(r []BadVideo) {
    r2 := append([]BadVideo(nil), r...)
    for i, j := range rand.Perm(len(r)) {
        r[i] = r2[j]
    }
}
</code>```

Try this variant on the Go Playground.

One thing to note here: before we do the reordering, we have to save the original slice (make a copy of it), so we can select the original elements specified by random indices when writing the results in the slice. I created a copy by appending the complete slice to a nil slice.

Body:
Here is my query :

c := session.DB("searchV").C("video")
var results []BadVideo
err5 := c.Find(nil).All(&results)
fmt.Println("request done")
if err5 != nil {
    panic(err5)
}
var i = 0
for _,badvideo := range results {
}

I would like to randomize the order of browsing the items of the query for making operation on each item of the request ...

So each time I run it, I browse it in a different order.

Body:
Manual shuffling

Here's a simple shuffle algorithm, which shuffles (randomizes) a []BadVido slice:

func shuffle(r []BadVideo) {
    for i := len(r) - 1; i > 0; i-- {
        j := rand.Intn(i + 1)
        r[i], r[j] = r[j], r[i]
    }
}

So after you loaded your results, simply call shuffle(results) on it.

For testing, I will use a simple BadVideo type:

type BadVideo struct {
    Name string
}

func main() {
    rand.Seed(time.Now().UnixNano())
    results := []BadVideo{{"a"}, {"b"}, {"c"}, {"d"}, {"e"}}
    shuffle(results)
    fmt.Println(results)
}

Output (try it on the Go Playground):

[{c} {d} {b} {e} {a}]

How it works:

To shuffle a slice, the shuffle() function randomly selects one element from the slice for each index. It does it like iterating over all elements downward, and selects a random element from the remaining slice (including index of the element we're currently selecting, because random orders also include ones where an element "stays in place"), and using a random index to swaps the element with the chosen random one. The loop goes until i > 0 (and not until i >=0), because if only 1 element left, no need to swap it with itself.

Using rand.Perm()

Another variant of shuffle() could take advantage of rand.Perm() which returns a slice containing shuffled numbers. We can use these random numbers to tell how to reorder the results:

func shuffle(r []BadVideo) {
    r2 := append([]BadVideo(nil), r...)
    for i, j := range rand.Perm(len(r)) {
        r[i] = r2[j]
    }
}

Try this variant on the Go Playground.

One thing to note here: before we do the reordering, we have to save the original slice (make a copy of it), so we can select the original elements specified by random indices when writing the results in the slice. I created a copy by appending the complete slice to a nil slice.


问:
How is eclipse feature to generate sample xml from an xsd schema implemented?
I'm curious how eclipse implements generating xml from an xsd schema, as described here:

http://help.eclipse.org/kepler/index.jsp?topic=%2Forg.eclipse.wst.xmleditor.doc.user%2Ftopics%2Ftcrexxsd.html

Is the source code available to view, to try and understand how this function is implemented?

答:
The wizard for Generate -> XML File is
the org.eclipse.wst.xml.ui.internal.wizards.NewXMLWizard class.
The generator under the hood is the org.eclipse.wst.xml.ui.internal.wizards.NewXMLGenerator class.
They are part of the
org.eclipse.wst.xml.ui plugin. Just follow the links to see the sources.


问:
Fedex Ruby Gem: Customs Value is required - how to add?
I'm working with the Ruby gem 'FedEx', https://github.com/jazminschroeder/fedex.
I've set up my code for a development mode and I'm testing making a shipment.

However, I get stuck with the following error:

C:/Ruby22/lib/ruby/gems/2.2.0/gems/fedex-.10.1/lib/fedex/request/shipment.rb:134:in 'failure_response': Customs Value is required. (Fedex:: RateError) from C: /Ruby22/lib/ruby/gems/2.2.0/gems/fedex-.10.1/lib/fedex/request/shipment.rb:32:in 'process_request' from C: /Ruby22/lib/ruby/gems/2.2.0/gems/fedex-3.10.1/lib/fedex/shipment.rb:57:in 'ship' from C: /Ruby22/bin/css_fedex_v1.rb:92:in ''

It seems that I need to parse a 'Customs Value', probably as part of my 'packages' hash. However, I'm unable to find the relevant field for me to enter this in. Anyone who's experienced this and found a solution?

My code is as below:

require 'fedex'

fedex = Fedex::Shipment.new(:key => '***',
                        :password => '***',
                        :account_number => '***',
                        :meter => '***',
                        :mode => 'development')

shipper = { :name => "***",
        :company => "***",
        :phone_number => "***",
        :address => "***",
        :city => "***",
        :postal_code => "***",
        :country_code => "DK" }

recipient = { :name => "***",
          :company => "***",
          :phone_number => "***",
          :address => "***",
          :city => "***",
          :postal_code => "***",
          :country_code => "GB",
          :residential => "false" }

packages = []
packages << {:weight => {:units => "LB", :value => 1}}

shipping_options = {:packaging_type => "YOUR_PACKAGING",
:drop_off_type => "REGULAR_PICKUP"}

rate = fedex.rate(:shipper=>shipper,
              :recipient => recipient,
              :packages => packages,
              :shipping_options => shipping_options)

ship = fedex.ship(:shipper=>shipper,
              :recipient => recipient,
              :packages => packages,
              :service_type => "INTERNATIONAL_PRIORITY",
              :shipping_options => shipping_options)
puts ship[:completed_shipment_detail][:operational_detail][:transit_time]
```

答:
Customs value is declared in their docs:
https://github.com/jazminschroeder/fedex/commit/9f1d4c67b829aaa4eeba9090c1a45d3bd507aab3#diff-4f122efb7c0d98120d8b7f0cd00998e4R106

```<code>customs_value = { :currency => "USD",
                   :amount => "200" }
</code>```

As I understand you can pass it into the commodities hash or keep it separate.

Body:
Customs value is declared in their docs:
https://github.com/jazminschroeder/fedex/commit/9f1d4c67b829aaa4eeba9090c1a45d3bd507aab3#diff-4f122efb7c0d98120d8b7f0cd00998e4R106

customs_value = { :currency => "USD",
                   :amount => "200" }

As I understand you can pass it into the commodities hash or keep it separate.


问:
How to decrypt blocks encrypted with RSA?
I'm still on my RSA project, and now I can successfully create the keys, and encrypt a string with them

```<code>def encrypt(clear_message, public_key):

    clear_list = convert_into_unicode (clear_message)

    n = public_key[0]
    e = public_key[1]

    message_chiffre = str()

    for i, value in enumerate (clear_list) :
        encrypted_value = str( pow (int(value), e, n) )

        encrypted_message += (encrypted_value )

    return encrypted_message

def convert_into_unicode (clear_message):

    str_unicode = ''

    for car in clear_message:
        str_unicode += str (ord (car))

    if len (str_unicode ) % 5 != 0:
        str_unicode += (5 - len (str_unicode ) % 5) * '0'

    clear_list = []

    i = 5

    while i <= len (str_unicode ):

        clear_list .append (str_unicode [i-5:i])

        i += 5

    return liste_claire
</code>```

For example, encrypting the message 'Hello World' returns ['72101', '10810', '81113', '28711', '11141', '08100', '32330'] as clear_list then
'3863   111   1616   3015   1202   341   4096' as encrypted_message

The encrypt () function uses the other function to convert the string into a list of the Unicode values but put in blocks because I've read that otherwise, it would be easy to find the clear message only with frequency analysis.

Is it really that easy?

And as it probably is, I come to my main question. As you know, the Unicode values of a character are either double-digits or triple-digits. Before the encryption, the Unicode values are separated into blocks of 5 digits ('stack' -> '115 116 97 99 107' -> '11511 69799 10700')

But the problem is when I want to decrypt this, how do I know where I have to separate that string so that one number represents one character?

I mean, the former Unicode value could be either 11 or 115 (I know it couldn't really be 11, but that's only as an example). So to decrypt and then get back the character, the problem is, I don't know how much digits I have to take.

I had thought of adding a 0 when the Unicode value is < 100, but

Then it's easy to do the same thing as before with the frequency analysis

Still, when I encrypt it, '087' can result in '467' and '089' can result in '046', so the problem is still here.

答:
Your convert_into_unicode function isn't really converting anything "into" Unicode.  Assuming clear_message is a Unicode string (The default string type in Python 3, or u'' in Python 2), it's (naturally) Unicode already, and you're using an awkward way of turning it into a sequence of bytes that you can encrypt.  If clear_message is a byte string (the default in Python 2, or b'' in Python 3), all the characters fit in a byte already, so the whole process is unnecessary.

It's true that Unicode string needs to be encoded as a byte sequence before you can encrypt it.  The normal way to do that is with an encoding such as UTF-8 or UTF-16.  You can do that by calling clear_message.encode('utf-8').  After decrypting, you can turn the decrypted byte string back into a Unicode string with decrypted_bytes.decode('utf-8').

You don't need the convert_into_unicode function at all.

Body:
I'm still on my RSA project, and now I can successfully create the keys, and encrypt a string with them

def encrypt(clear_message, public_key):

    clear_list = convert_into_unicode (clear_message)

    n = public_key[0]
    e = public_key[1]

    message_chiffre = str()

    for i, value in enumerate (clear_list) :
        encrypted_value = str( pow (int(value), e, n) )

        encrypted_message += (encrypted_value )

    return encrypted_message

def convert_into_unicode (clear_message):

    str_unicode = ''

    for car in clear_message:
        str_unicode += str (ord (car))

    if len (str_unicode ) % 5 != 0:
        str_unicode += (5 - len (str_unicode ) % 5) * '0'

    clear_list = []

    i = 5

    while i <= len (str_unicode ):

        clear_list .append (str_unicode [i-5:i])

        i += 5

    return liste_claire

For example, encrypting the message 'Hello World' returns ['72101', '10810', '81113', '28711', '11141', '08100', '32330'] as clear_list then
'3863   111   1616   3015   1202   341   4096' as encrypted_message

The encrypt () function uses the other function to convert the string into a list of the Unicode values but put in blocks because I've read that otherwise, it would be easy to find the clear message only with frequency analysis.

Is it really that easy?

And as it probably is, I come to my main question. As you know, the Unicode values of a character are either double-digits or triple-digits. Before the encryption, the Unicode values are separated into blocks of 5 digits ('stack' -> '115 116 97 99 107' -> '11511 69799 10700')

But the problem is when I want to decrypt this, how do I know where I have to separate that string so that one number represents one character?

I mean, the former Unicode value could be either 11 or 115 (I know it couldn't really be 11, but that's only as an example). So to decrypt and then get back the character, the problem is, I don't know how much digits I have to take.

I had thought of adding a 0 when the Unicode value is < 100, but

Then it's easy to do the same thing as before with the frequency analysis

Still, when I encrypt it, '087' can result in '467' and '089' can result in '046', so the problem is still here.


问:
Htaccess and url for multilingual site
I'm ready to use the subdirectory format for my multilingual website.
My first question is:
For SEO, have I to translate the page name in the url or it is useless?
Example:

```<code>- Same filename
site.com/fr/login
site.com/en/login
</code>```

OR

```<code>- Different filename
site.com/fr/connexion
site.com/en/login
</code>```

Then, when user is on site.com: Should I redirect him to site.com/en and site.com/fr depending user's IP? Or have I to set a default local, and have my url like site.com/page and site.com/fr/page

Finally, what is the best way to get the local from user's current URL?
Parsing url to get /fr or /en, or add a GET parameter in url with lang=fr (hidden with htaccess)

Thanks :)

答:
As a precondition, I assume that you are not using frameworks / libraries. Furthermore, I never have solved similar problems only using .htaccess (as the title of your question requests) and thus don't know if it is possible to do so. Nevertheless, the following guidelines may help you.

Your first question

In general, a web page's file name and path have influence on its ranking. Furthermore, having page names and paths in native languages might help your users memorize the most important of your URLs even without bookmarking them.

Nevertheless, I never would translate the page names or directories for pages which are part of a web application (as opposed to a informational or promotional pages).

The login page you mentioned is a good example. I am nearly sure that you do not want your site to be found because of its contents on its login page. Actually, there are many websites which exclude login pages and other application pages from being indexed at all.

Instead, in SEO terms, put your effort into your promotional and informational pages. Provide valuable content, explain what is special about you or your site, and do everything you could that those pages get properly indexed. IMHO, static HTML pages are the best choice for doing so.

Furthermore, if you translate the names of pages which belong to your actual application, you will run into massive trouble. For example, after successful login, your application probably will transfer the user to his personal dashboard, which probably will be based on another HTML template / page. If you have translated that page name into different languages, then your application will have to take care to take the user to the right version. Basically, that means that you need as many versions of your application as languages you want to support. Of course, there are tricks to make life easier, but this will be a constant pain and definitely in no way worth the effort.

To summarize: Create static pages which show your USP (unique seller position) and provide valuable content to users (for example sophisticated tutorials and so on). Translate those pages, including names and paths, and SEO them in every way you could. But regarding the actual application, optimizing its pages is kind of pointless and even counterproductive.

Your second question

I would never use IP based redirecting for several reasons.

First, there are many customers in countries which are not their home country. For example, do you really want to redirect all native English speakers to your Hungarian pages because they are currently in Hungary for a business trip?

Second, more and more users today are using VPNs for different reasons, thereby often hiding the country where they currently are.

Third, which IP address belongs to which provider or country is highly volatile; you would have to constantly update your databases to keep up.

There are more reasons, but I think you already have got the idea.

Fortunately, there is a solution to your problem (but see "Final remark" below): Every browser, when fetching a page from a server, tells the server the preferred and accepted languages. For example, Apache can directly use that information in RewriteRule statements and redirect the user to the correct page.

If you can't alter your Server's configuration, then you can evaluate the respective header in your CGI program.

When doing your research, look for the Accept-Language HTTP 1.1 header. A good starting point probably is here.

Your third question

You eventually are mixing up two different things in your third question. A locale is not the same as a language. On one hand, you are asking "...to get the local from...", and on the other hand, you say "...lang=fr...", thus making the impression you want to get the language.

If you want to get the language: See my answer to your second question, or parse the language from the current path (as you already have suggested).

If you want to get the locale, things are more complicated. The only reasonable automatic method is to derive the locale from the language, but this will often fail. For example, I generally prefer the English language when doing research, but on the other hand, I am located in Germany and thus would like dates and times in the format I am used to, so deriving my desired locale from my preferred language will fail.

Unfortunately, there is no HTTP header which could tell the server which locale the user prefers. As a starting point, this article may help you.

See the final remark (next section) on how to solve this problem.

Final remark

As the article linked above already states: The only reliable way to satisfy the user is to let him choose his language, his locale and his time zone within your application. You could store the user's choices either in cookies or in your back-end database; each has its own advantages and disadvantages.

I usually use a combination of all methods (HTTP headers, cookies, database) in my projects.

Title: Htaccess and url for multilingual site

Body:
I'm ready to use the subdirectory format for my multilingual website.
My first question is:
For SEO, have I to translate the page name in the url or it is useless?
Example:

- Same filename
site.com/fr/login
site.com/en/login

OR

- Different filename
site.com/fr/connexion
site.com/en/login

Then, when user is on site.com: Should I redirect him to site.com/en and site.com/fr depending user's IP? Or have I to set a default local, and have my url like site.com/page and site.com/fr/page

Finally, what is the best way to get the local from user's current URL?
Parsing url to get /fr or /en, or add a GET parameter in url with lang=fr (hidden with htaccess)

Thanks :)


问:
Determining if a position is free in a Closed Hashing
How would you go about determining whether a position is already occupied or not? When the memory is allocated, all that there is in it is garbage (in C++, which is what I'm using atm). I was thinking of using an auxiliary array of bools to know whether the position is occupied, but that would demand quite a lot of additional memory.

I could also set a value for every position, but then I wouldn't be able to use said value. In both cases, I would also lose some performance initializing the values (the bools to false, the other values to 0 to indicate the position is free, for example).

Any other solutions?

答:
Usually, you use a special placeholder element to indicate empty values. In the simplest case, this could be a null pointer but that would of course mean that you introduce an indirection; you can't store your values directly. In all other cases you would have to make allowance for the type actually stored. For example, if you stored 32 bit integers, you would have to reserve at least one predefined value (e.g. 0) as a sentinel element, thus reducing the range of values that may be stored in your hash table.

An additional array with flags is quite a good solution. Consider that this array could be reduced by a factor of at least 8 by storing bit flags instead of whole-byte variables (or even bools, which would require 4 bytes each on most architectures).

OwnerDisplayName: al bundy

LastEditorDisplayName: AnthonyWJones

OwnerDisplayName: Konrad Rudolph

LastEditorDisplayName: Konrad Rudolph


问:
Generate PDF of page using alternate/print stylesheet
I want to generate a PDF of a webpage but apply an alternate, print-type stylesheet to it instead of the styles it uses now. Say, for example, I have a button on http://eorailway.co.uk to generate a PDF of the same page (which is run and administered by me, so therefore I can include any PHP/JS necessary to each page) but I want to apply alternate styling to it before generating the PDF.

At the moment I am using the dompdf PHP library to generate the PDF using the normal/default stylesheet, but cannot for the life of me think how to apply the alternate stylesheet to the page when clicking the "Generate PDF" button.

Any advice is most appreciated.

答:
In the 0.6.0 release of DOMPDF you can specify the stylesheet to use by modifying the DOMPDF_DEFAULT_MEDIA_TYPE configuration constant.

http://code.google.com/p/dompdf/source/browse/trunk/dompdf/dompdf_config.inc.php?r=336#234


问:
How to Query between a date range in MySQL

I'm querying

```<code>SELECT * FROM tempLog WHERE date BETWEEN '23-03-2017' AND '02-04-2017'
</code>```

and the result is null. How to fix this. But

```<code>SELECT * FROM tempLog WHERE date BETWEEN '23-03-2017' AND '30-03-2017'
</code>```

giving me the correct result.
Note:- tempLog is the table name.

答:
You should store dates in date format or atleast correctly formatted string (YYYY-MM-DD).

For now you can use str_to_date to convert the string to date and compare:

```<code>select *
from tempLog
where str_to_date(date, '%d-%m-%Y') between '2017-03-23' and '2017-04-02';
</code>```

However note that this will hinder the optimizer from using index on the column if any.

The correct remedy of the situation is fixing the table structure.

Body:
I'm querying

SELECT * FROM tempLog WHERE date BETWEEN '23-03-2017' AND '02-04-2017'

and the result is null. How to fix this. But

SELECT * FROM tempLog WHERE date BETWEEN '23-03-2017' AND '30-03-2017'

giving me the correct result.
Note:- tempLog is the table name.

Body:
You should store dates in date format or atleast correctly formatted string (YYYY-MM-DD).

For now you can use str_to_date to convert the string to date and compare:

select *
from tempLog
where str_to_date(date, '%d-%m-%Y') between '2017-03-23' and '2017-04-02';

However note that this will hinder the optimizer from using index on the column if any.

The correct remedy of the situation is fixing the table structure.


问:
Installing an R package from local unzipped folder
I am having difficulty installing an unzipped package on a Windows 7 computer without administrative privileges and no internet access. I am using the RGui (not RStudio).

Right now I have an unzipped library sitting in a directory. Unfortunately, when I try:

```<code>install.packages("C://path//to//directory",
    repos = NULL,
    lib = "C://path//to//newDirectory")
</code>```

I am getting the error:

```<code>Warning in `install.packages("C://path//to//directory",`   :
   'lib = "C://path//to//newDirectory"' is not writable
</code>```

Which is strange because I do have write privileges to where I am attempting to store the package.

When I get this error, I also get a popup from RGui:

```<code>Would you like to use a personal library instead?
</code>```

If I click Yes, it throws the error:

```<code>Error in `install.packages("C://path//to//directory",`   :
    type == "both" cannot be used with 'repos = NULL'
</code>```

I also cannot install devtools. Any ideas?

答: If it is an unzipped Windows binary (e.g., from CRAN), you can just copy and paste the entire package directory into your library folder. You could also, presumably, use file.copy() to do so if you wanted to do it within R. install.packages() is failing (weirdly) because you're giving it something other than the typical package source or zipped binary that it is expecting.

Body:
I am having difficulty installing an unzipped package on a Windows 7 computer without administrative privileges and no internet access. I am using the RGui (not RStudio).

Right now I have an unzipped library sitting in a directory. Unfortunately, when I try:

install.packages("C://path//to//directory",
    repos = NULL,
    lib = "C://path//to//newDirectory")

I am getting the error:

Warning in `install.packages("C://path//to//directory",`   :
   'lib = "C://path//to//newDirectory"' is not writable

Which is strange because I do have write privileges to where I am attempting to store the package.

When I get this error, I also get a popup from RGui:

Would you like to use a personal library instead?

If I click Yes, it throws the error:

Error in `install.packages("C://path//to//directory",`   :
    type == "both" cannot be used with 'repos = NULL'

I also cannot install devtools. Any ideas?


问:
Sorting an array by providing an array of pointers as arguments
I wrote this code, but it is only giving me an address of something:

```<code>#include<iostream>
using namespace std;

void swap(int* a,int* b)
{
    int temp=*a;
    *a=*b;
    *b=temp;
}

void sort(int* p[],int n)
{
    for(int i=0; i<n;i++)
    {
        if(*p[i]>*p[i+1])
        swap(p[i],p[i+1]);
    }
}

int main()
{
    int arr[]={8,6,5,4,3,7,1};
    int* p[7];

    for(int i=0;i<7;i++)
    {
        p[i]=&arr[i];
    }

    sort(p,7);

    /*i tried to change arr[1] to p[1] or *p[1] but same output*/
    cout<<arr[1]<<arr[2];
    return 0;
}
</code>```

I think I'm lacking in concept somewhere. The complete question is this:

Write the following function that indirectly sorts the floats pointed to by the first n pointers in the array p by rearranging the pointers: void sort(float* p[],int n)

Please help.

答:
First of your code has a buffer overflow, which means undefined behaviour and anything it does is therefore by definition correct. In sort the index i goes over all array positions from 0 to n-1. But then you access i+1, which is one element beyond the array. For me the code segfaults.

Correcting this the output is "54" and here is what happens.

The swap function swaps the values in arr instead of swapping the pointers in p. The exercise asks you to indirectly sort the array, menaing the pointers. You need to use ** or *& there. So what happens in the sort loop is that 8 and 6 are swapped, then 8 and 5 are swapped and 8 and 4 are swapped and so on. So your array then is {6,5,4,3,7,1,8}. Last you output arr[1] and [2], which is 5 and 4. Since you don't output a space between them you get "54".

Body:
I wrote this code, but it is only giving me an address of something:

#include<iostream>
using namespace std;

void swap(int* a,int* b)
{
    int temp=*a;
    *a=*b;
    *b=temp;
}

void sort(int* p[],int n)
{
    for(int i=0; i<n;i++)
    {
        if(*p[i]>*p[i+1])
        swap(p[i],p[i+1]);
    }
}

int main()
{
    int arr[]={8,6,5,4,3,7,1};
    int* p[7];

    for(int i=0;i<7;i++)
    {
        p[i]=&arr[i];
    }

    sort(p,7);

    /*i tried to change arr[1] to p[1] or *p[1] but same output*/
    cout<<arr[1]<<arr[2];
    return 0;
}

I think I'm lacking in concept somewhere. The complete question is this:

Write the following function that indirectly sorts the floats pointed to by the first n pointers in the array p by rearranging the pointers: void sort(float* p[],int n)

Please help.


问:
socialite Google Login shows "The page isn’t redirecting properly"
I am trying to setup Google Login using socialite in Laravel. But when I enter the Google credentials, it shows:

The page isn’t redirecting properly

for  the url http://127.0.0.1:8000/redirect/google.

My web.php is:

```<code>Route::get('/redirect/google', 'SocialAuthController@redirect');
Route::get('/callback/google', 'SocialAuthController@callback');
</code>```

services.php:

```<code>'google' => [
    'client_id' => '-----.apps.googleusercontent.com',
    'client_secret' => '---------',
    'redirect' => 'http://127.0.0.1:8000/callback/google'
],
</code>```

SocialAuthController.php:

```<code>namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\SocialAccountService;
use Socialite;

class SocialAuthController extends Controller {
    //
    public function redirect(){
        return Socialite::driver('google')->redirect();
    }

    public function callback(SocialAccountService $service) {
        $user = $service->createOrGetUser(Socialite::driver('google')->user());
        auth()->login($user);
        return redirect()->back();
    }
}
</code>```

SocialAccount.php :

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class SocialAccount extends Model {
    //
    protected $fillable = ['user_id', 'provider_user_id', 'provider'];

    public function user() {
        return $this->belongsTo(User::class);
    }
}
</code>```

Migration for social_accounts_table

```<code>class CreateSocialAccountsTable extends Migration {
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up() {
        Schema::create('social_accounts', function (Blueprint $table) {
            $table->increments('user_id');
            $table->string('provider_user_id');
            $table->string('provider');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down() {
        Schema::dropIfExists('social_accounts');
    }
}
</code>```

SocialAccountService.php

```<code>namespace App;

use Laravel\Socialite\Contracts\User as ProviderUser;

class SocialAccountService {
    public function createOrGetUser(ProviderUser $providerUser) {
        $account = SocialAccount::whereProvider('google')
            ->whereProviderUserId($providerUser->getId())
            ->first();

        if ($account) {
            return $account->user;
        } else {
            $account = new SocialAccount([
                'provider_user_id' => $providerUser->getId(),
                'provider' => 'google'
            ]);

            $user = User::whereEmail($providerUser->getEmail())->first();

            if (!$user) {
                $user = User::create([
                    'email' => $providerUser->getEmail(),
                    'name' => $providerUser->getName(),
                    'role' => 'user',
                    'password' => '',
                ]);
            }

            $account->user()->associate($user);
            $account->save();
            return $user;
        }

    }
}
</code>```

答:
In your services, you have

```<code>'redirect' => 'http://127.0.0.1:8000/callback/google'
</code>```

After authentication, Google cannot access your domain http://127.0.0.1(localhost). You will have to try it with a production URL

Body:
I am trying to setup Google Login using socialite in Laravel. But when I enter the Google credentials, it shows:

The page isn’t redirecting properly

for  the url http://127.0.0.1:8000/redirect/google.

My web.php is:

Route::get('/redirect/google', 'SocialAuthController@redirect');
Route::get('/callback/google', 'SocialAuthController@callback');

services.php:

'google' => [
    'client_id' => '-----.apps.googleusercontent.com',
    'client_secret' => '---------',
    'redirect' => 'http://127.0.0.1:8000/callback/google'
],

SocialAuthController.php:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\SocialAccountService;
use Socialite;

class SocialAuthController extends Controller {
    //
    public function redirect(){
        return Socialite::driver('google')->redirect();
    }

    public function callback(SocialAccountService $service) {
        $user = $service->createOrGetUser(Socialite::driver('google')->user());
        auth()->login($user);
        return redirect()->back();
    }
}

SocialAccount.php :

namespace App;

use Illuminate\Database\Eloquent\Model;

class SocialAccount extends Model {
    //
    protected $fillable = ['user_id', 'provider_user_id', 'provider'];

    public function user() {
        return $this->belongsTo(User::class);
    }
}

Migration for social_accounts_table

class CreateSocialAccountsTable extends Migration {
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up() {
        Schema::create('social_accounts', function (Blueprint $table) {
            $table->increments('user_id');
            $table->string('provider_user_id');
            $table->string('provider');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down() {
        Schema::dropIfExists('social_accounts');
    }
}

SocialAccountService.php

namespace App;

use Laravel\Socialite\Contracts\User as ProviderUser;

class SocialAccountService {
    public function createOrGetUser(ProviderUser $providerUser) {
        $account = SocialAccount::whereProvider('google')
            ->whereProviderUserId($providerUser->getId())
            ->first();

        if ($account) {
            return $account->user;
        } else {
            $account = new SocialAccount([
                'provider_user_id' => $providerUser->getId(),
                'provider' => 'google'
            ]);

            $user = User::whereEmail($providerUser->getEmail())->first();

            if (!$user) {
                $user = User::create([
                    'email' => $providerUser->getEmail(),
                    'name' => $providerUser->getName(),
                    'role' => 'user',
                    'password' => '',
                ]);
            }

            $account->user()->associate($user);
            $account->save();
            return $user;
        }

    }
}

Body:
In your services, you have

'redirect' => 'http://127.0.0.1:8000/callback/google'

After authentication, Google cannot access your domain http://127.0.0.1(localhost). You will have to try it with a production URL


问:
Parse one field from nested Json to String Value
i have one field nested JSON in my API response :

```<code>"ratingBest": 10,
"reviewCount": 1,
"coordinate": {
    "latitude": "-7.2768",
    "longitude": "112.7927"
},
...
</code>```

I save above data to Android local DB using ORMLite, but i want just one field coordinate to be String. Cause Gson automatically convert in specific type.

I already try to use a class field type as String. But still not work

Any workaround for that?

Thank you

答:
Try this.

```<code>var a = {
  "ratingBest": 10,
  "reviewCount": 1,
  "coordinate": {
    "latitude": "-7.2768",
    "longitude": "112.7927"
 }
}

var b = {
  "ratingBest": 10,
  "reviewCount": 1,
  "coordinate": JSON.stringify(a.coordinate)
}
</code>```

now store b

Body:
i have one field nested JSON in my API response :

"ratingBest": 10,
"reviewCount": 1,
"coordinate": {
    "latitude": "-7.2768",
    "longitude": "112.7927"
},
...

I save above data to Android local DB using ORMLite, but i want just one field coordinate to be String. Cause Gson automatically convert in specific type.

I already try to use a class field type as String. But still not work

Any workaround for that?

Thank you

Body:
Try this.

var a = {
  "ratingBest": 10,
  "reviewCount": 1,
  "coordinate": {
    "latitude": "-7.2768",
    "longitude": "112.7927"
 }
}

var b = {
  "ratingBest": 10,
  "reviewCount": 1,
  "coordinate": JSON.stringify(a.coordinate)
}

now store b


问:
How can instanceof be preformed inside a method with no specific object?
My code is full of things like this:

```<code>Block attackedBlock = (fixtureA.getUserData() instanceof  Block) ?  (Block) fixtureA.getUserData() :  (Block) fixtureB.getUserData();
Bullet bullet       = (fixtureA.getUserData() instanceof Bullet) ? (Bullet) fixtureA.getUserData() : (Bullet) fixtureB.getUserData();
</code>```

And this works, but it's quite messy IMO, so I made a method to shorten the lines:

```<code>Fixture getFixture(Class USER_DATA) {
    return (fixtureA.getUserData() instanceof USER_DATA) ? fixtureA : fixtureB;
}
</code>```

I get the error that USER_DATA isn't a class, which is understandable, but how do I make it look in the specified class? It also says that that condiotion will always evaluate to false/ What should I do?

答:
You should do this instead:</p>

```<code> USER_DATA.isInstance(fixtureA.getUserData())
</code>```

Body:
My code is full of things like this:

Block attackedBlock = (fixtureA.getUserData() instanceof  Block) ?  (Block) fixtureA.getUserData() :  (Block) fixtureB.getUserData();
Bullet bullet       = (fixtureA.getUserData() instanceof Bullet) ? (Bullet) fixtureA.getUserData() : (Bullet) fixtureB.getUserData();

And this works, but it's quite messy IMO, so I made a method to shorten the lines:

Fixture getFixture(Class USER_DATA) {
    return (fixtureA.getUserData() instanceof USER_DATA) ? fixtureA : fixtureB;
}

I get the error that USER_DATA isn't a class, which is understandable, but how do I make it look in the specified class? It also says that that condiotion will always evaluate to false/ What should I do?

Body:
You should do this instead:

 USER_DATA.isInstance(fixtureA.getUserData())


问:
DB2 extract with vbscript
i want to extract data from db2 mainframe which uses IBM code page 285 (EBCDIC code page)
 with vbscript but saving this file (xml data) it displays wrong way.
 How can i convert vbscript RecSet from 285 to ASCII or UTF-8 before saving file?

```<code>Function used for saving file:
Function WriteFileText( sText, sFileName)
    Dim sFilePath
Dim objFSO 'As FileSystemObject
Dim objTextFile 'As Object
    Dim i
    Dim arr

sFilePath = "c:\jdk1.3\temp\" & sFileName
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.CreateTextFile(sFilePath, True, True)

a = 0

for i=1 to len(sText)
s2Text = right(left(sText,i),1)
if i > 54 and asc(s2Text) = 63 then a = a + 1 else objTextFile.Write (s2Text) end if
next

objTextFile.Close
</code>```

''    Set objTextFile = objFSO.CreateTextFile(sFilePath, True, True)
''    used to convert to UTF8, as if only one True error appears when writing to file

答: See How to convert between ASCII and EBCDIC character codes. It's written in VB but whould be easy to convert to VBScript.</p>

Title: DB2 extract with vbscript

Body:
i want to extract data from db2 mainframe which uses IBM code page 285 (EBCDIC code page)
 with vbscript but saving this file (xml data) it displays wrong way.
 How can i convert vbscript RecSet from 285 to ASCII or UTF-8 before saving file?

Function used for saving file:
Function WriteFileText( sText, sFileName)
    Dim sFilePath
Dim objFSO 'As FileSystemObject
Dim objTextFile 'As Object
    Dim i
    Dim arr

sFilePath = "c:\jdk1.3\temp\" & sFileName
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.CreateTextFile(sFilePath, True, True)

a = 0

for i=1 to len(sText)
s2Text = right(left(sText,i),1)
if i > 54 and asc(s2Text) = 63 then a = a + 1 else objTextFile.Write (s2Text) end if
next

objTextFile.Close

''    Set objTextFile = objFSO.CreateTextFile(sFilePath, True, True)
''    used to convert to UTF8, as if only one True error appears when writing to file


问:
Getting value of internal div when outside div is clicked
I have the following: A bunch of button div's which each have unique info

```<code><div class="button">
  <div id="first">
      Johny
  </div>
  <div id="second">
      Dog
  </div>
  <div id="third">
      Pasta
  </div>
</div>
<div class="button">
  <div id="first">
      Bob
  </div>
  <div id="second">
      Cat
  </div>
  <div id="third">
      Noodles
  </div>
</div>
   .
   .
   .
</code>```

I'm trying to make it so that when one of these buttons is clicked, i can check the values of the inner divs.

For instance

```<code>$('.button').on('click', function () {
     // Check to see if the text of the 'first' div is
     // johnny or bob or something else
});
</code>```

答:
How about giving each div its own click handler? (you will need unique ids for this to work properly)</p>

```<code><script type="text/javascript">
    var bchildren = $('.button').children();
    $(bchildren).click(function() {
        console.log($(this).html());
    });
    }
</script>
</code>```

Body:
I have the following: A bunch of button div's which each have unique info

      Johny

      Dog

      Pasta

      Bob

      Cat

      Noodles

   .
   .
   .

I'm trying to make it so that when one of these buttons is clicked, i can check the values of the inner divs.

For instance

$('.button').on('click', function () {
     // Check to see if the text of the 'first' div is
     // johnny or bob or something else
});

Body:
How about giving each div its own click handler? (you will need unique ids for this to work properly)

<script type="text/javascript">
    var bchildren = $('.button').children();
    $(bchildren).click(function() {
        console.log($(this).html());
    });
    }
</script>


问:
is there a way to bcp SQL data, pipe it to 7z Compressor and then pipe it AZcopy without dumping to intermediate files?
The reason why I want to do this is we have a big table which is well partitioned and wanted to upload to blob storage very quickly by breaking down into multiple pieces using BCP, zipping it using 7z and upload it with AZCopy. Each thread handles each piece but the problem with this approach is it creates multiple intermediate files which in turn creates huge disk queue length & takes a significant amount of time writing to disk. I am looking for a solution which completely bypasses creating those files locally in the disk and directly uploads them. Any idea?</p>

答:
About BCP, until 7zip'ping
May be, through variable.

In Power Shell:
$A = $(bcp << ... actions>>).

$A will be containing result of bcp request.
If 7zip supports API of cmd.exe, piping there. e.t.c.


问:
applying transformation matrix to a list of points in opencv (Python)
I'm failing to understand the documentation for cv2.transform. Will someone take pity and explain please (in Python)?

I have code that draws a polygon, fills it in, and rotates the image

```<code>import numpy as np
import cv2

dx,dy = 400,400
centre = dx//2,dy//2
img = np.zeros((dy,dx),np.uint8)

# construct a long thin triangle with the apex at the centre of the image
polygon = np.array([(0,0),(100,10),(100,-10)],np.int32)
polygon += np.int32(centre)

# draw the filled-in polygon and then rotate the image
cv2.fillConvexPoly(img,polygon,(255))
M = cv2.getRotationMatrix2D(centre,20,1) # M.shape =  (2, 3)
rotatedimage = cv2.warpAffine(img,M,img.shape)
</code>```

I want to rotate the polygon first and then draw it

```<code># this is clumsy, I have to extend each vector,
# apply the matrix to each extended vector,
# and turn the list of transformed vectors into an numpy array
extendedpolygon = np.hstack([polygon,np.ones((3,1))])
rotatedpolygon = np.int32([M.dot(x) for x in extendedpolygon])
cv2.fillConvexPoly(img,rotatedpolygon,(127))
</code>```

I'd like to do it in one function call but I can't get it right

```<code># both of these calls produce the same error
cv2.transform(polygon,M)
cv2.transform(polygon.T,M)
# OpenCV Error: Assertion failed (scn == m.cols || scn + 1 == m.cols) in transform, file /home/david/opencv/modules/core/src/matmul.cpp, line 1947
</code>```

I suspect that it's the phrase "src – input array that must have as many channels (1 to 4) as m.cols or m.cols-1" that I'm floundering on. I thought that polygon.T as three coordinates with the x and y parts as separate channels would qualify, but sadly not.

I'm aware that the same question has been asked for C++, I want an answer in Python.

答:
My thanks to Micka who pointed me to a working example. Here is code that provides an answer to my question.

```<code>import numpy as np
import cv2

dx,dy = 400,400
centre = dx//2,dy//2
img = np.zeros((dy,dx),np.uint8)

# construct a long thin triangle with the apex at the centre of the image
polygon = np.array([(0,0),(100,10),(100,-10)],np.int32)
polygon += np.int32(centre)

# draw the filled-in polygon and then rotate the image
cv2.fillConvexPoly(img,polygon,(255))
M = cv2.getRotationMatrix2D(centre,20,1) # M.shape =  (2, 3)
rotatedimage = cv2.warpAffine(img,M,img.shape)

# as an alternative, rotate the polygon first and then draw it

# these are alternative ways of coding the working example
# polygon.shape is 3,2

# magic that makes sense if one understands numpy arrays
poly1 = np.reshape(polygon,(3,1,2))
# slightly more accurate code that doesn't assumy the polygon is a triangle
poly2 = np.reshape(polygon,(polygon.shape[0],1,2))
# turn each point into an array of points
poly3 = np.array([[p] for p in polygon])
# use an array of array of points
poly4 = np.array([polygon])
# more magic
poly5 = np.reshape(polygon,(1,3,2))

for poly in (poly1,poly2,poly3,poly4,poly5):
    newimg = np.zeros((dy,dx),np.uint8)
    rotatedpolygon = cv2.transform(poly,M)
    cv2.fillConvexPoly(newimg,rotatedpolygon,(127))
</code>```

To be honest, I don't understand why cv2.fillConvexPoly() accepts the first three answers but it seems to be very forgiving and I still don't understand how these answers map to the documentation.

Body:
I'm failing to understand the documentation for cv2.transform. Will someone take pity and explain please (in Python)?

I have code that draws a polygon, fills it in, and rotates the image

import numpy as np
import cv2

dx,dy = 400,400
centre = dx//2,dy//2
img = np.zeros((dy,dx),np.uint8)

# construct a long thin triangle with the apex at the centre of the image
polygon = np.array([(0,0),(100,10),(100,-10)],np.int32)
polygon += np.int32(centre)

# draw the filled-in polygon and then rotate the image
cv2.fillConvexPoly(img,polygon,(255))
M = cv2.getRotationMatrix2D(centre,20,1) # M.shape =  (2, 3)
rotatedimage = cv2.warpAffine(img,M,img.shape)

I want to rotate the polygon first and then draw it

# this is clumsy, I have to extend each vector,
# apply the matrix to each extended vector,
# and turn the list of transformed vectors into an numpy array
extendedpolygon = np.hstack([polygon,np.ones((3,1))])
rotatedpolygon = np.int32([M.dot(x) for x in extendedpolygon])
cv2.fillConvexPoly(img,rotatedpolygon,(127))

I'd like to do it in one function call but I can't get it right

# both of these calls produce the same error
cv2.transform(polygon,M)
cv2.transform(polygon.T,M)
# OpenCV Error: Assertion failed (scn == m.cols || scn + 1 == m.cols) in transform, file /home/david/opencv/modules/core/src/matmul.cpp, line 1947

I suspect that it's the phrase "src – input array that must have as many channels (1 to 4) as m.cols or m.cols-1" that I'm floundering on. I thought that polygon.T as three coordinates with the x and y parts as separate channels would qualify, but sadly not.

I'm aware that the same question has been asked for C++, I want an answer in Python.

Body:
My thanks to Micka who pointed me to a working example. Here is code that provides an answer to my question.

import numpy as np
import cv2

dx,dy = 400,400
centre = dx//2,dy//2
img = np.zeros((dy,dx),np.uint8)

# construct a long thin triangle with the apex at the centre of the image
polygon = np.array([(0,0),(100,10),(100,-10)],np.int32)
polygon += np.int32(centre)

# draw the filled-in polygon and then rotate the image
cv2.fillConvexPoly(img,polygon,(255))
M = cv2.getRotationMatrix2D(centre,20,1) # M.shape =  (2, 3)
rotatedimage = cv2.warpAffine(img,M,img.shape)

# as an alternative, rotate the polygon first and then draw it

# these are alternative ways of coding the working example
# polygon.shape is 3,2

# magic that makes sense if one understands numpy arrays
poly1 = np.reshape(polygon,(3,1,2))
# slightly more accurate code that doesn't assumy the polygon is a triangle
poly2 = np.reshape(polygon,(polygon.shape[0],1,2))
# turn each point into an array of points
poly3 = np.array([[p] for p in polygon])
# use an array of array of points
poly4 = np.array([polygon])
# more magic
poly5 = np.reshape(polygon,(1,3,2))

for poly in (poly1,poly2,poly3,poly4,poly5):
    newimg = np.zeros((dy,dx),np.uint8)
    rotatedpolygon = cv2.transform(poly,M)
    cv2.fillConvexPoly(newimg,rotatedpolygon,(127))

To be honest, I don't understand why cv2.fillConvexPoly() accepts the first three answers but it seems to be very forgiving and I still don't understand how these answers map to the documentation.


问:
Functional way to take element in a list until a limit in Scala
The aim of the method is to take elements in a list until a limit is reached.

e.g.

I've come up with 2 different implementations

```<code>def take(l: List[Int], limit: Int): List[Int] = {
  var sum = 0
  l.takeWhile { e =>
    sum += e
    sum <= limit
  }
}
</code>```

It is straightforward, but a mutable state is used.

```<code>def take(l: List[Int], limit: Int): List[Int] = {
  val summed = l.toStream.scanLeft(0) { case (e, sum) => sum + e }
  l.take(summed.indexWhere(_ > limit) - 1)
}
</code>```

It seems cleaner, but it's more verbose and perhaps less memory efficient because a stream is needed.

Is there a better way ?

答:
The first way is perfectly fine as the result of your function is still perfectly immutable.

On a side note, this is actually how many functions of the scala collection library are implemented, they create a mutable builder for efficiency and return an immutable collection out of it.

Body:
The aim of the method is to take elements in a list until a limit is reached.

e.g.

I've come up with 2 different implementations

def take(l: List[Int], limit: Int): List[Int] = {
  var sum = 0
  l.takeWhile { e =>
    sum += e
    sum <= limit
  }
}

It is straightforward, but a mutable state is used.

def take(l: List[Int], limit: Int): List[Int] = {
  val summed = l.toStream.scanLeft(0) { case (e, sum) => sum + e }
  l.take(summed.indexWhere(_ > limit) - 1)
}

It seems cleaner, but it's more verbose and perhaps less memory efficient because a stream is needed.

Is there a better way ?


问:
Android SQLITE Insert into table with values coming from a subquery
In my db-driven app I need to perform insert into queries in which the value for one or more field comes from a subquery.

The insert into statement may look like the following example:

```<code>INSERT INTO MyTable (field_1, field_2)
VALUES('value for field 1', (SELECT field_x FROM AnotherTable WHERE ...))
</code>```

At present I am doing it manually building the query:

```<code>String MyQuery = "INSERT INTO mytable (field_1, field_2)
    VALUES('value for field 1', (SELECT field_x FROM AnotherTable WHERE ...))"; // Of course my query is far more complex and is built in several steps but the concept is safe, I end up with a SQL String

SQLiteDatabase= db = getWritableDatabase();

db.execSQL(MyQuery); // And it works flawlessy as it was a Swiss Clock
</code>```

What i would like to do instead is:

```<code>SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();

values.put("field_1", "value for field 1");
values.put("field_2", ThisIsAQuery("(SELECT field_x FROM AnotherTable WHERE ...)"));

db.insert("MyTable", null, values);
db.close();
</code>```

Where the fake method ThisIsAQuery(...) is the missing part, something that should tell the query builder that "SELECT.." is not a value but a query that should be embedded in the insert statement.

Is there a way to achieve this?

答:
The whole point of the ContentValues container is to be able to safely use strings without interpreting them as SQL commands.

It is not possible to use subqueries with insert(). The only way to get a value from another table is by executing a separate query; in this case, ThisIsAQuery() would be stringForQuery() or longForQuery().

Body:
In my db-driven app I need to perform insert into queries in which the value for one or more field comes from a subquery.

The insert into statement may look like the following example:

INSERT INTO MyTable (field_1, field_2)
VALUES('value for field 1', (SELECT field_x FROM AnotherTable WHERE ...))

At present I am doing it manually building the query:

String MyQuery = "INSERT INTO mytable (field_1, field_2)
    VALUES('value for field 1', (SELECT field_x FROM AnotherTable WHERE ...))"; // Of course my query is far more complex and is built in several steps but the concept is safe, I end up with a SQL String

SQLiteDatabase= db = getWritableDatabase();

db.execSQL(MyQuery); // And it works flawlessy as it was a Swiss Clock

What i would like to do instead is:

SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();

values.put("field_1", "value for field 1");
values.put("field_2", ThisIsAQuery("(SELECT field_x FROM AnotherTable WHERE ...)"));

db.insert("MyTable", null, values);
db.close();

Where the fake method ThisIsAQuery(...) is the missing part, something that should tell the query builder that "SELECT.." is not a value but a query that should be embedded in the insert statement.

Is there a way to achieve this?


问:
SUM of Specific Duplicates in a long list of duplicates
I want to sum specific duplicates from a column. in fact, I have 7 columns of people names(About 1,000 names in each column but they all repeat between 10-180 times). I have a list of 25 specific people that I need to find how many times their names have repeated into that particular column and I don’t need the sum of the remaining names. I guess once I have the formula to apply for one column, I should be able to copy paste it on the columns where I need my answers.

Can i have some help in applying an appropriate formula please? I tried sumif but is coming back as an error.

答:
Try use the COUNTIF function.

```<code>  | A      | B      | C      | D | E              | F     |
1 | Names 1| Names 2| Names 3|   | Names to Count | Count |
  |--------|--------|--------|   |----------------|-------|
2 | Alice  | Bob    | Malcom |   | Alice          |  4    |
3 | Alice  | Alice  | Malcom |   | Bob            |  6    |
4 | Malcom | Bob    | Bob    |   | Total          | 10    |
5 | Bob    | Malcom | Bob    |
6 | Alice  | Malcom | Bob    |
</code>```

To do the counting use the following function:

```<code>=COUNTIF(table, name) // Where table is your table of names,
                      // and name is the name to count.

// In my example this would be as follows:
=COUNTIF($A$2:$C$6; E2) // for Alice
=COUNTIF($A$2:$C$6; E3) // for Bob
=SUM(F2:F3)             // for total
</code>```

Body:
Try use the COUNTIF function.

  | A      | B      | C      | D | E              | F     |
1 | Names 1| Names 2| Names 3|   | Names to Count | Count |
  |--------|--------|--------|   |----------------|-------|
2 | Alice  | Bob    | Malcom |   | Alice          |  4    |
3 | Alice  | Alice  | Malcom |   | Bob            |  6    |
4 | Malcom | Bob    | Bob    |   | Total          | 10    |
5 | Bob    | Malcom | Bob    |
6 | Alice  | Malcom | Bob    |

To do the counting use the following function:

=COUNTIF(table, name) // Where table is your table of names,
                      // and name is the name to count.

// In my example this would be as follows:
=COUNTIF($A$2:$C$6; E2) // for Alice
=COUNTIF($A$2:$C$6; E3) // for Bob
=SUM(F2:F3)             // for total


问:
Facing this issue @driver.quit giving error in after (:context ) in rspec
I am trying this

```<code>require 'rspec'
require 'selenium-webdriver'

RSpec.describe 'New test' do

  before :each do
    @driver = Selenium::WebDriver.for (:firefox)
  end

  after :all do
    @driver.quit
  end

  it 'should signup and create a new user' do
    p 'testing'
  end
end
</code>```

And this is the error I get

```<code>rspec test.rb                                                                                [13:04:18]
"testing"
.
An error occurred in an `after(:context)` hook.
Failure/Error: @driver.quit

NoMethodError:
  undefined method `quit' for nil:NilClass
# ./test.rb:11:in `block (2 levels) in <top (required)>'

Finished in 4.61 seconds (files took 0.17828 seconds to load)
1 example, 0 failures
</code>```

I am sure it is a small thing that i am missing but could not find it any help would be appreciated.

Is this a FF or selenium version issue?

I am using FF 45 and selenium 2.53 and rspec 3.5.4.

答:
This is an RSpec issue.  before/after(:all) hooks only have access to instance variables defined in their scope or outer scope levels, but not to instance variables declared in the current spec being run.  after(:each) hooks do have access to the instance variables declared in the current spec.</p>

```<code>before :all do
 @a = 2
end

context "blah" do
  before :all do
    @b = 3
  end

  it "blah blah" do
    @c = 4
    # @a,@b,@c all accessible here
  end

  after :each do
   #@a, @b, @c accessible here
  end

  after :all do
    # @a,@b  accessible here
  end
end

after :all do
   #can access @a
end
</code>```

Body:
I am trying this

require 'rspec'
require 'selenium-webdriver'

RSpec.describe 'New test' do

  before :each do
    @driver = Selenium::WebDriver.for (:firefox)
  end

  after :all do
    @driver.quit
  end

  it 'should signup and create a new user' do
    p 'testing'
  end
end

And this is the error I get

rspec test.rb                                                                                [13:04:18]
"testing"
.
An error occurred in an `after(:context)` hook.
Failure/Error: @driver.quit

NoMethodError:
  undefined method `quit' for nil:NilClass
# ./test.rb:11:in `block (2 levels) in <top (required)>'

Finished in 4.61 seconds (files took 0.17828 seconds to load)
1 example, 0 failures

I am sure it is a small thing that i am missing but could not find it any help would be appreciated.

Is this a FF or selenium version issue?

I am using FF 45 and selenium 2.53 and rspec 3.5.4.

Body:
This is an RSpec issue.  before/after(:all) hooks only have access to instance variables defined in their scope or outer scope levels, but not to instance variables declared in the current spec being run.  after(:each) hooks do have access to the instance variables declared in the current spec.

before :all do
 @a = 2
end

context "blah" do
  before :all do
    @b = 3
  end

  it "blah blah" do
    @c = 4
    # @a,@b,@c all accessible here
  end

  after :each do
   #@a, @b, @c accessible here
  end

  after :all do
    # @a,@b  accessible here
  end
end

after :all do
   #can access @a
end


问:
Loading system properties for tests
I recently found a solution that allows me to load system properties for my unit tests. It works great if I'm running a test individually, but if I choose to run the whole test suite, it fails. Can someone tell me why?

The first step is to load the test application context:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test.xml")
</code>```

The next step is to create a class which will load the system properties:

```<code>import java.io.InputStream;
import java.util.Properties;

import javax.annotation.PostConstruct;

import org.springframework.core.io.Resource;

public class SystemPropertiesLoader{

    private Resource resource;

    public void setResource(final Resource resource){
        this.resource = resource;
    }

    @PostConstruct
    public void applyProperties() throws Exception{

        final Properties systemProperties = System.getProperties();

        final InputStream inputStream = resource.getInputStream();

        try{
            systemProperties.load(inputStream);
        } finally{
            inputStream.close();
        }
    }
}
</code>```

The final step is to list this as a bean in my test application context:

```<code><bean class="com.foo.SystemPropertiesLoader">
    <property name="resource" value="classpath:localdevelopment_Company.properties" />
</bean>
</code>```

When I run the test suite, several of my tests, all of which rely on system properties, fail. If I go to the specific test and run it, it will pass. I've debugged it and I've verified that the code in SystemPropertiesLoader is being executed, and all other beans are being pulled successfully from the context. However, the properties are not being loaded correctly, as they are all coming up null when I try to access them. Any suggestions?

答:
Could it be possible that each of your test cases is spawning a new JVM, and the System properties are not being set for each test case?

Maybe try to leverage the setUp() and tearDown() methods in your JUnit test class.

Title: Loading system properties for tests

Body:
I recently found a solution that allows me to load system properties for my unit tests. It works great if I'm running a test individually, but if I choose to run the whole test suite, it fails. Can someone tell me why?

The first step is to load the test application context:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-test.xml")

The next step is to create a class which will load the system properties:

import java.io.InputStream;
import java.util.Properties;

import javax.annotation.PostConstruct;

import org.springframework.core.io.Resource;

public class SystemPropertiesLoader{

    private Resource resource;

    public void setResource(final Resource resource){
        this.resource = resource;
    }

    @PostConstruct
    public void applyProperties() throws Exception{

        final Properties systemProperties = System.getProperties();

        final InputStream inputStream = resource.getInputStream();

        try{
            systemProperties.load(inputStream);
        } finally{
            inputStream.close();
        }
    }
}

The final step is to list this as a bean in my test application context:

<bean class="com.foo.SystemPropertiesLoader">
    <property name="resource" value="classpath:localdevelopment_Company.properties" />
</bean>

When I run the test suite, several of my tests, all of which rely on system properties, fail. If I go to the specific test and run it, it will pass. I've debugged it and I've verified that the code in SystemPropertiesLoader is being executed, and all other beans are being pulled successfully from the context. However, the properties are not being loaded correctly, as they are all coming up null when I try to access them. Any suggestions?