问:
How to download the most updated java virtual machine(Hotspot) source code?
I am going to contribute to Java Community and I am interested in JVM.

Now I would like to download the most updated JVM Hotspot source code and track the updates.

First, I go to http://openjdk.java.net/ .

On its left side I find some useful tag

```<code>Source code:
Mercurial
Bundles
...
JDK 6
JDK 7
JDK 7 Updates
JDK 8 · Java SE 8
JDK 8 Updates
JDK 9 · Java SE 9
JDK 10
</code>```

I can only find instruction about how to download source code of JDK8u: http://openjdk.java.net/projects/jdk8u/

Status

We're open for fixes for 8u152 in the jdk8u-dev forest. (The post time is 2017-06-06 14:23:36)

Source code

The jdk8u-dev forest for ongoing development can be cloned using this command: hg clone http://hg.openjdk.java.net/jdk8u/jdk8u-dev;cd jdk8u-dev;sh get_source.sh .

The corresponding master forest jdk8u can be cloned using this command: hg clone http://hg.openjdk.java.net/jdk8u/jdk8u;cd jdk8u;sh get_source.sh .

In addition, the source code for the last release, 8u102, is available by cloning the 8u master forest : http://hg.openjdk.java.net/jdk8u/jdk8u and using the 'jdk8u102-b14' mercurial tag.

But it appears that jdk9 and jdk10 are also on the list. Are they the most updated source code and how can I download them?

JDK9 page does not provide instructions about how to get source code.
JDK9 : http://hg.openjdk.java.net/jdk9

JDK10: http://openjdk.java.net/projects/jdk10/

Besides, if the Java Community release a new update, what is the best way to update my current source code? Download again or use Mercurial tool?

What is forest in jdk source code? Is it similar to branch in git？

Also, I can find another way to download JVM Hotspot source code from github in JetBrains:

https://github.com/JetBrains/jdk8u_hotspot/tree/d37547149a7c5647ebffbbb62525cc62bd8e2673

But I am not sure this one is the most updated one.

答:
This depends on what you mean by 'most updated'.

Actually, all of jdk8u, jdk9 and jdk10 repositories are kept up-to-date; they are just separate projects having different status and accepting different set of changes.

jdk8u has the most recent changes that will appear in the future updates of JDK 8. These updates mainly consist of bug fixes.

jdk9 repository contains up-to-date code that will be released soon as JDK 9. The project is now in Rampdown phase 2 meaning that only showstopper bugs can be fixed there. It's not defined yet what will happen to this repository after JDK 9 release - e.g. give start for something like jdk9u.

jdk10 contains the ongoing work on future version of Java SE platform. Important improvements made here are likely to be backported to jdk9 sometime later (of course, if they comply with the specifications).

Note that new features are not developed directly in this repository. New features must go through JEP process. Some bigger features may be even hosted in separate projects like Panama or Valhalla.

The official repositories of OpenJDK projects are hosted at http://hg.openjdk.java.net

To get the sources use Mercurial, e.g.

```<code>hg clone http://hg.openjdk.java.net/jdk10/jdk10
</code>```

It contains several nested repositories. HotSpot JVM is under hotspot:

```<code>hg clone http://hg.openjdk.java.net/jdk10/jdk10/hotspot
</code>```

Later you can use hg pull -u to sync your local repository with the updates from the master.

In the parent repository you'll also find the instructions how to get the sources and to build OpenJDK: common/doc/building.md. There is a similar document in jdk9 repo.

Body:
I am going to contribute to Java Community and I am interested in JVM.

Now I would like to download the most updated JVM Hotspot source code and track the updates.

First, I go to http://openjdk.java.net/ .

On its left side I find some useful tag

Source code:
Mercurial
Bundles
...
JDK 6
JDK 7
JDK 7 Updates
JDK 8 · Java SE 8
JDK 8 Updates
JDK 9 · Java SE 9
JDK 10

I can only find instruction about how to download source code of JDK8u: http://openjdk.java.net/projects/jdk8u/

Status

We're open for fixes for 8u152 in the jdk8u-dev forest. (The post time is 2017-06-06 14:23:36)

Source code

The jdk8u-dev forest for ongoing development can be cloned using this command: hg clone http://hg.openjdk.java.net/jdk8u/jdk8u-dev;cd jdk8u-dev;sh get_source.sh .

The corresponding master forest jdk8u can be cloned using this command: hg clone http://hg.openjdk.java.net/jdk8u/jdk8u;cd jdk8u;sh get_source.sh .

In addition, the source code for the last release, 8u102, is available by cloning the 8u master forest : http://hg.openjdk.java.net/jdk8u/jdk8u and using the 'jdk8u102-b14' mercurial tag.

But it appears that jdk9 and jdk10 are also on the list. Are they the most updated source code and how can I download them?

JDK9 page does not provide instructions about how to get source code.
JDK9 : http://hg.openjdk.java.net/jdk9

JDK10: http://openjdk.java.net/projects/jdk10/

Besides, if the Java Community release a new update, what is the best way to update my current source code? Download again or use Mercurial tool?

What is forest in jdk source code? Is it similar to branch in git？

Also, I can find another way to download JVM Hotspot source code from github in JetBrains:

https://github.com/JetBrains/jdk8u_hotspot/tree/d37547149a7c5647ebffbbb62525cc62bd8e2673

But I am not sure this one is the most updated one.

Body:
This depends on what you mean by 'most updated'.

Actually, all of jdk8u, jdk9 and jdk10 repositories are kept up-to-date; they are just separate projects having different status and accepting different set of changes.

jdk8u has the most recent changes that will appear in the future updates of JDK 8. These updates mainly consist of bug fixes.

jdk9 repository contains up-to-date code that will be released soon as JDK 9. The project is now in Rampdown phase 2 meaning that only showstopper bugs can be fixed there. It's not defined yet what will happen to this repository after JDK 9 release - e.g. give start for something like jdk9u.

jdk10 contains the ongoing work on future version of Java SE platform. Important improvements made here are likely to be backported to jdk9 sometime later (of course, if they comply with the specifications).

Note that new features are not developed directly in this repository. New features must go through JEP process. Some bigger features may be even hosted in separate projects like Panama or Valhalla.

The official repositories of OpenJDK projects are hosted at http://hg.openjdk.java.net

To get the sources use Mercurial, e.g.

hg clone http://hg.openjdk.java.net/jdk10/jdk10

It contains several nested repositories. HotSpot JVM is under hotspot:

hg clone http://hg.openjdk.java.net/jdk10/jdk10/hotspot

Later you can use hg pull -u to sync your local repository with the updates from the master.

In the parent repository you'll also find the instructions how to get the sources and to build OpenJDK: common/doc/building.md. There is a similar document in jdk9 repo.


来源: stackexchange

问:
crystal report - Subtract result for each item
On Crystal Report, I want to show
My_Qty, which is {Table.1st_Qty}-{Table.2nd_qty}, for each item.

My desired outcome is

```<code>Item 1   5  0  5(My_Qty_1)
Item 2   6  0  6(My_Qty_2)
</code>```

But my current CR shows

```<code>Item 1   5  0  11
Item 2   6  0  11
</code>```

Is there anyway that I can adjust {Table.1st_Qty}-{Table.2nd_qty} to print out what I want?

I have tried 'Running Total Fields' but no luck. I've been googling around but can't find an answer for my case.
Thank you so much in advance!

答:
use whileprintingrecords:

It will do sum while reading data from start to end.

ContentLicense: CC BY-SA 3.0

Body:
On Crystal Report, I want to show
My_Qty, which is {Table.1st_Qty}-{Table.2nd_qty}, for each item.

My desired outcome is

Item 1   5  0  5(My_Qty_1)
Item 2   6  0  6(My_Qty_2)

But my current CR shows

Item 1   5  0  11
Item 2   6  0  11

Is there anyway that I can adjust {Table.1st_Qty}-{Table.2nd_qty} to print out what I want?

I have tried 'Running Total Fields' but no luck. I've been googling around but can't find an answer for my case.
Thank you so much in advance!


问:
Remove several rows based on one row
In the data.frame below, I have 3 variables. id (A1 to A10); var A to E and value. I want to remove specific rows based on these conditions

For each variable var (A, B, C, D or E);

If id == A5 and

if value < 5

then

remove all rows (10 rows) for this specific variable.

I will appreciate any suggestions how to do that.

```<code>> dput(df)
structure(list(id = structure(c(1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L,
10L, 2L, 1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 2L, 1L, 3L, 4L,
5L, 6L, 7L, 8L, 9L, 10L, 2L, 1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L,
10L, 2L, 1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 2L), .Label = c("A1",
"A10", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"), class = "factor"),
    var = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
    5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L), .Label = c("A",
    "B", "C", "D", "E"), class = "factor"), value = c(2, 4, 7,
    8, 8, 6, 3, 8, 4, 2, 3, 5, 4, 3, 2, 7, 4, 2, 1, 22, 54, 21,
    36, 52, 14, 75, 12, 15, 24, 3, 2, 4, 5, 7, 9, 21, 22, 12,
    12, 12, 0.3, 0.4, 0.9, 2, 3, 2, 0.5, 0.2, 0.4, 0.7)), .Names = c("id",
"var", "value"), class = "data.frame", row.names = c(NA, -50L
))
</code>```

答:
well you can always do</p>

```<code>df %>% filter((id != A5) | (value >= 5))
</code>```

Title: Remove several rows based on one row

Body:
In the data.frame below, I have 3 variables. id (A1 to A10); var A to E and value. I want to remove specific rows based on these conditions

For each variable var (A, B, C, D or E);

If id == A5 and

if value < 5

then

remove all rows (10 rows) for this specific variable.

I will appreciate any suggestions how to do that.

> dput(df)
structure(list(id = structure(c(1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L,
10L, 2L, 1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 2L, 1L, 3L, 4L,
5L, 6L, 7L, 8L, 9L, 10L, 2L, 1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L,
10L, 2L, 1L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 2L), .Label = c("A1",
"A10", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9"), class = "factor"),
    var = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
    5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L), .Label = c("A",
    "B", "C", "D", "E"), class = "factor"), value = c(2, 4, 7,
    8, 8, 6, 3, 8, 4, 2, 3, 5, 4, 3, 2, 7, 4, 2, 1, 22, 54, 21,
    36, 52, 14, 75, 12, 15, 24, 3, 2, 4, 5, 7, 9, 21, 22, 12,
    12, 12, 0.3, 0.4, 0.9, 2, 3, 2, 0.5, 0.2, 0.4, 0.7)), .Names = c("id",
"var", "value"), class = "data.frame", row.names = c(NA, -50L
))

Body:
well you can always do

df %>% filter((id != A5) | (value >= 5))


问:
How to extract directory path from file path?
In Bash, if VAR="/home/me/mydir/file.c", how do I get "/home/me/mydir"?

答:
I was playing with this and came up with an alternative.

```<code>$ VAR=/home/me/mydir/file.c

$ DIR=`echo $VAR |xargs dirname`

$ echo $DIR
/home/me/mydir
</code>```

The part I liked is it was easy to extend backup the tree:

```<code>$ DIR=`echo $VAR |xargs dirname |xargs dirname |xargs dirname`

$ echo $DIR
/home
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I was playing with this and came up with an alternative.

$ VAR=/home/me/mydir/file.c

$ DIR=`echo $VAR |xargs dirname`

$ echo $DIR
/home/me/mydir

The part I liked is it was easy to extend backup the tree:

$ DIR=`echo $VAR |xargs dirname |xargs dirname |xargs dirname`

$ echo $DIR
/home


问:
AForge, memory stacking up
Im trying to grab a frame with C# and AForge libraries:

```<code>...
using AForge.Video
using AForge.Video.DirectShow

namespace Example
{
     class Program
     {

      private static Bitmap mySnap = null;

      static void Main(string[] args)
      {
             snapByte();
      }

      private static void snapByte()
      {
                    int Counter = 0;
                    FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
                    VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);
                    videoSource.NewFrame += new NewFrameEventHandler(videoNewFrame);
                    videoSource.Start();
                    do
                    {
                        Thread.Sleep(500);
                        Counter++;
                    }
                    while (mySnap == null && Counter < 4);
                    if (videoSource.IsRunning)
                    {
                        videoSource.SignalToStop();
                        videoSource.WaitForStop();
                        videoSource = null;
                    }
                    MemoryStream myStream = new MemoryStream();
                    mySnap.Save(myStream, ImageFormat.Png);
                    byte[] snapByteLength = MyStream.ToArray();
                    int snapLength = snapByteLength.Length;
                    Console.WriteLine(snapLength);
                    Console.ReadLine();
                    myStream.Dispose();
                    mySnap = null;
                    snapByte();
            }
        }

        private static void videoNewFrame(object sender, NewFrameEventArgs eventArgs)
        {
             mySnap = (Bitmap)eventArgs.Frame.Clone();
        }
   }
}
</code>```

this is the exact code im using, i just changed the image byte processing to display the byte length to simplify things..

the problem im having is that the memory will keep staking up anywhere between 1-2 mb each time a snapshot is taken..
i am disposing of all my bitmaps except for the mySnap that im returning to null.. i cant dispose of mySnap because its used again, and i have to declare it global because i use this in snapByte() and newVideoFrame()
but since im reusing mySnap i dont see why would it be stacking up.. it should be overwriting everytime..

i have seen other answers but all have to do with a picturebox, and the answer is to clear the picturebox before loading a new image..
i believe im doing the equivalent here by calling mySnap=null again..
but memory still stacking up...

Thank You..

答:
You are creating an infinite recursion by your unconditional call to snapByte() at the end of the snapByte() method.  This creates a loop that will eventually crash once your stack runs out of space; every time your method calls itself, you are setting up a new stack frame that will never be cleared because the method never returns.  This may take a while to manifest because of the Thread.Sleep() call that will keep your recursive calls throttled.

Also, any reference that was not nulled before you recursively call snapByte() will be held indefinitely in memory, since those references are alive in a scope that will never exit (because of the infinite recursion) and will never be reclaimed by the GC.

This is the case for your videoDevices collection but more importantly for the snapByteLength array instance, that is holding a copy of the bitmap you just captured.  I bet this is the primary cause for your memory leak

Avoiding recursion and converting it to a simple loop should fix your issues.

Title: AForge, memory stacking up

Body:
Im trying to grab a frame with C# and AForge libraries:

...
using AForge.Video
using AForge.Video.DirectShow

namespace Example
{
     class Program
     {

      private static Bitmap mySnap = null;

      static void Main(string[] args)
      {
             snapByte();
      }

      private static void snapByte()
      {
                    int Counter = 0;
                    FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
                    VideoCaptureDevice videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);
                    videoSource.NewFrame += new NewFrameEventHandler(videoNewFrame);
                    videoSource.Start();
                    do
                    {
                        Thread.Sleep(500);
                        Counter++;
                    }
                    while (mySnap == null && Counter < 4);
                    if (videoSource.IsRunning)
                    {
                        videoSource.SignalToStop();
                        videoSource.WaitForStop();
                        videoSource = null;
                    }
                    MemoryStream myStream = new MemoryStream();
                    mySnap.Save(myStream, ImageFormat.Png);
                    byte[] snapByteLength = MyStream.ToArray();
                    int snapLength = snapByteLength.Length;
                    Console.WriteLine(snapLength);
                    Console.ReadLine();
                    myStream.Dispose();
                    mySnap = null;
                    snapByte();
            }
        }

        private static void videoNewFrame(object sender, NewFrameEventArgs eventArgs)
        {
             mySnap = (Bitmap)eventArgs.Frame.Clone();
        }
   }
}

this is the exact code im using, i just changed the image byte processing to display the byte length to simplify things..

the problem im having is that the memory will keep staking up anywhere between 1-2 mb each time a snapshot is taken..
i am disposing of all my bitmaps except for the mySnap that im returning to null.. i cant dispose of mySnap because its used again, and i have to declare it global because i use this in snapByte() and newVideoFrame()
but since im reusing mySnap i dont see why would it be stacking up.. it should be overwriting everytime..

i have seen other answers but all have to do with a picturebox, and the answer is to clear the picturebox before loading a new image..
i believe im doing the equivalent here by calling mySnap=null again..
but memory still stacking up...

Thank You..


问:
where to find libstdc++.so.5 32-BIT version for SLES 12 on PPC64LE
I need to install on SLES 12 SP2 for IBM PPC64LE the 32-bit version of libstdc++.so.5 and of libstdc++.so.6.

Do you know if they exist and where to find them?

I looked on google but i find only x86 version, i need PPC64LE version.

答:
I suspect most of the distros are no longer shipping support for 32-bit environments on POWER, particularly after the change to little-endian. In fact, I don't think there was ever an official 32-bit little-endian ELF ABIv2 defined.

The SLES folks have a brief document  on 32-bit compatibility, which includes the following about POWER:

We would note that SLES for Power systems with the change from big endian in SLES 11 to little endian in SLES 12, is ready in SLES 12 for 64-bit applications where that build environment is fully available. For ISVs currently providing 32-bit applications, having their customers run the 32-bit application on SLES 11 in a virtual image is a good option for their customers running SLES 12 on Power 8 as their base system.

That first sentence is a bit hard to parse, but it seems like they no longer ship support for 32-bit on LE.

Do you need to build 32-bit?


问:
SVG Logo on Microsoft Edge is showing 10 times bigger than other browsers
I am using a svg logo for my website, as shown below:

```<code><img alt="" class="logo logo-dark" src="images/logo-dark.svg">
</code>```

The svg file contains the following information about the size:

```<code><svg xmlns="http://www.w3.org/2000/svg" viewBox="-274.1 380.7 46 41.9" width="40">
</code>```

to determine the width.

Even though it is shown correctly in all browsers, in Microsoft Edge it is shown 10 times bigger.

What am I missing out?

Update: The .logo has max-width:100%

答:
Instead of using the width in the svg, use it in the img tag like this:

```<code><img alt="" class="logo logo-dark" src="images/logo-dark.svg" width="40">
</code>```

You can also set both height and width on the svg instead of only width.

Body:
I am using a svg logo for my website, as shown below:

The svg file contains the following information about the size:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="-274.1 380.7 46 41.9" width="40">

to determine the width.

Even though it is shown correctly in all browsers, in Microsoft Edge it is shown 10 times bigger.

What am I missing out?

Update: The .logo has max-width:100%

Body:
Instead of using the width in the svg, use it in the img tag like this:

<img alt="" class="logo logo-dark" src="images/logo-dark.svg" width="40">

You can also set both height and width on the svg instead of only width.


问:
Exrin: How to setup two way binding between VisualState and ModelState
How is the binding between ModelState and VisualState changed from one way to two way?

In the Exrin introduction on YouTube and in this SO answer, it is stated that there is a binding between the ModelState and the VisualState (specifically ModelState -> VisualState). It is also stated that the binding can be changed from one way to two way.

I did some looking around and did find a BindingType enum with the values being OneWay and TwoWay, but I was unable to find where to utilize these.

答:
In the VisualState you can add this attribute to any property.

```<code>[Binding(BindingType.TwoWay)]
public int PropertyName { get { Get<int>(); } set { Set(value); } }
</code>```

If there is no attribute it defaults to OneWay binding.

Body:
In the VisualState you can add this attribute to any property.

[Binding(BindingType.TwoWay)]
public int PropertyName { get { Get<int>(); } set { Set(value); } }

If there is no attribute it defaults to OneWay binding.


答:
We can do this with dplyr using group_by and filter, we remove the group (var) which has any occurrence of id as "A5" and value less than 5.

```<code>library(dplyr)
df %>%
   group_by(var) %>%
   filter(!any(id == 'A5' & value < 5))
</code>```

Title: Remove several rows based on one row

Body:
We can do this with dplyr using group_by and filter, we remove the group (var) which has any occurrence of id as "A5" and value less than 5.

library(dplyr)
df %>%
   group_by(var) %>%
   filter(!any(id == 'A5' & value < 5))


问:
Which lib to use? libmariadbclient or libmysqlclient?
For some unknown reason, my libmysqlclient.a disappeared in my CentOS 7.
My program then got linker error, saying cannot find libmysqlclient.

And then I discovered that my mysql-devel package is gone:

```<code>yum info mysql-devel
yum install mysql-devel
</code>```

Here is the response:

```<code>Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: repo.virtualhosting.hk
 * epel: mirror.pregi.net
 * extras: repo.virtualhosting.hk
 * updates: repo.virtualhosting.hk
Package MariaDB-devel-10.2.5-1.el7.centos.x86_64 already installed and latest version
</code>```

So I think maybe I should use libmariadbclient instead, but when I link my program with libmariadbclient, it had linking errors:

```<code>/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x191): undefined reference to `CRYPTO_num_locks'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x1aa): undefined reference to `CRYPTO_THREADID_set_callback'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x1b6): undefined reference to `CRYPTO_set_locking_callback'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x1bb): undefined reference to `SSL_library_init'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x1c7): undefined reference to `SSL_load_error_strings'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x1cc): undefined reference to `OPENSSL_add_all_algorithms_noconf'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x2b4): undefined reference to `CRYPTO_set_locking_callback'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x2bb): undefined reference to `CRYPTO_set_id_callback'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x2df): undefined reference to `CRYPTO_num_locks'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x340): undefined reference to `EVP_cleanup'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x345): undefined reference to `CRYPTO_cleanup_all_ex_data'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x34a): undefined reference to `ERR_free_strings'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x351): undefined reference to `CONF_modules_free'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_init':
(.text+0x3e1): undefined reference to `SSLv23_client_method'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `my_cb_threadid':
(.text+0x1e): undefined reference to `CRYPTO_THREADID_set_numeric'
/usr/lib64//libmariadbclient.a(ma_compress.c.o): In function `_mariadb_compress_alloc':
(.text+0x5d): undefined reference to `compress'
/usr/lib64//libmariadbclient.a(ma_compress.c.o): In function `_mariadb_uncompress':
(.text+0x191): undefined reference to `uncompress'
collect2: error: ld returned 1 exit status
</code>```

I've been using libmysqlclient to connect with my MariaDB 10.1, and have recently been trying to build it from source, but failed due to problems with OpenSSL 1.1 version. Here you see my another post for it:

Error "incomplete type MD5_CONTEXT" with MariaDB 10.2 and Openssl 1.1.0e

So I'm confused why mysqlclient.a disappeared and which lib I should use.

Can anyone help?

Thanks!

答:
I had the similar problem when tried to compile my program with "-lmariadbclient" (after apt-get update -lmysqlclient stopped working).
The Makefile I used was:

```<code>g++ -std=c++11 *.cpp ../common/*.cpp ../common/*.c -o myprogram -I.. -ldl -Wstack-protector -fstack-protector-all -pthread -ggdb -lssl -lcrypto -lz -lmariadbclient -Wwrite-strings  -fPIC
</code>```

I read that commands "-lssl -lcrypto -lz" must be added to fix those errors, but I put them in the wrong place (before lmariadbclient). When I added them after "-lmariadbclient" I was finally able to compile my program:

```<code>g++ -std=c++11 *.cpp ../common/*.cpp ../common/*.c -o myprogram -I.. -ldl -Wstack-protector -fstack-protector-all -pthread -ggdb -lmariadbclient -Wwrite-strings -lssl -lcrypto -lz -fPIC
</code>```

UPDATE 22.07.2017:

I recently tried to compile my program on the new Linux Mint 18.2. Unfortunately I was getting the same compilation errors, and I was unable to fix it with the old method:

MariaDB version:

```<code> mysql --version
 mysql  Ver 15.1 Distrib 10.2.7-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2
</code>```

Compile errors:

```<code>/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x189): undefined reference to `CRYPTO_num_locks'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x1a4): undefined reference to `CRYPTO_THREADID_set_callback'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x1b0): undefined reference to `CRYPTO_set_locking_callback'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x1b5): undefined reference to `SSL_library_init'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x1c1): undefined reference to `SSL_load_error_strings'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x1c6): undefined reference to `OPENSSL_add_all_algorithms_noconf'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x2a4): undefined reference to `CRYPTO_set_locking_callback'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x2ab): undefined reference to `CRYPTO_set_id_callback'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x2cf): undefined reference to `CRYPTO_num_locks'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x330): undefined reference to `EVP_cleanup'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x335): undefined reference to `CRYPTO_cleanup_all_ex_data'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x33a): undefined reference to `ERR_free_strings'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x33f): undefined reference to `CONF_modules_free'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_init':
(.text+0x3c1): undefined reference to `SSLv23_client_method'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `my_cb_threadid':
(.text+0x1e): undefined reference to `CRYPTO_THREADID_set_numeric'
</code>```

I managed to fix it by changing "-lmariadbclient" to: "-lmariadb". After that I was able to compile my program with no errors. I'm not sure if this solution will work for everyone, but worth to try :)

My final Makefile is:

```<code>g++ -std=c++11 *.cpp ../common/*.cpp ../common/*.c -o myprogram -I.. -ldl -Wstack-protector -fstack-protector-all -pthread -ggdb -lmariadb -Wwrite-strings -lssl -lcrypto -lz -fPIC
</code>```

Good luck!

Body:
For some unknown reason, my libmysqlclient.a disappeared in my CentOS 7.
My program then got linker error, saying cannot find libmysqlclient.

And then I discovered that my mysql-devel package is gone:

yum info mysql-devel
yum install mysql-devel

Here is the response:

Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: repo.virtualhosting.hk
 * epel: mirror.pregi.net
 * extras: repo.virtualhosting.hk
 * updates: repo.virtualhosting.hk
Package MariaDB-devel-10.2.5-1.el7.centos.x86_64 already installed and latest version

So I think maybe I should use libmariadbclient instead, but when I link my program with libmariadbclient, it had linking errors:

/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x191): undefined reference to `CRYPTO_num_locks'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x1aa): undefined reference to `CRYPTO_THREADID_set_callback'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x1b6): undefined reference to `CRYPTO_set_locking_callback'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x1bb): undefined reference to `SSL_library_init'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x1c7): undefined reference to `SSL_load_error_strings'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x1cc): undefined reference to `OPENSSL_add_all_algorithms_noconf'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x2b4): undefined reference to `CRYPTO_set_locking_callback'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x2bb): undefined reference to `CRYPTO_set_id_callback'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x2df): undefined reference to `CRYPTO_num_locks'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x340): undefined reference to `EVP_cleanup'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x345): undefined reference to `CRYPTO_cleanup_all_ex_data'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x34a): undefined reference to `ERR_free_strings'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x351): undefined reference to `CONF_modules_free'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `ma_tls_init':
(.text+0x3e1): undefined reference to `SSLv23_client_method'
/usr/lib64//libmariadbclient.a(openssl.c.o): In function `my_cb_threadid':
(.text+0x1e): undefined reference to `CRYPTO_THREADID_set_numeric'
/usr/lib64//libmariadbclient.a(ma_compress.c.o): In function `_mariadb_compress_alloc':
(.text+0x5d): undefined reference to `compress'
/usr/lib64//libmariadbclient.a(ma_compress.c.o): In function `_mariadb_uncompress':
(.text+0x191): undefined reference to `uncompress'
collect2: error: ld returned 1 exit status

I've been using libmysqlclient to connect with my MariaDB 10.1, and have recently been trying to build it from source, but failed due to problems with OpenSSL 1.1 version. Here you see my another post for it:

Error "incomplete type MD5_CONTEXT" with MariaDB 10.2 and Openssl 1.1.0e

So I'm confused why mysqlclient.a disappeared and which lib I should use.

Can anyone help?

Thanks!

Body:
I had the similar problem when tried to compile my program with "-lmariadbclient" (after apt-get update -lmysqlclient stopped working).
The Makefile I used was:

g++ -std=c++11 *.cpp ../common/*.cpp ../common/*.c -o myprogram -I.. -ldl -Wstack-protector -fstack-protector-all -pthread -ggdb -lssl -lcrypto -lz -lmariadbclient -Wwrite-strings  -fPIC

I read that commands "-lssl -lcrypto -lz" must be added to fix those errors, but I put them in the wrong place (before lmariadbclient). When I added them after "-lmariadbclient" I was finally able to compile my program:

g++ -std=c++11 *.cpp ../common/*.cpp ../common/*.c -o myprogram -I.. -ldl -Wstack-protector -fstack-protector-all -pthread -ggdb -lmariadbclient -Wwrite-strings -lssl -lcrypto -lz -fPIC

UPDATE 22.07.2017:

I recently tried to compile my program on the new Linux Mint 18.2. Unfortunately I was getting the same compilation errors, and I was unable to fix it with the old method:

MariaDB version:

 mysql --version
 mysql  Ver 15.1 Distrib 10.2.7-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2

Compile errors:

/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x189): undefined reference to `CRYPTO_num_locks'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x1a4): undefined reference to `CRYPTO_THREADID_set_callback'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x1b0): undefined reference to `CRYPTO_set_locking_callback'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x1b5): undefined reference to `SSL_library_init'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x1c1): undefined reference to `SSL_load_error_strings'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_start':
(.text+0x1c6): undefined reference to `OPENSSL_add_all_algorithms_noconf'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x2a4): undefined reference to `CRYPTO_set_locking_callback'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x2ab): undefined reference to `CRYPTO_set_id_callback'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x2cf): undefined reference to `CRYPTO_num_locks'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x330): undefined reference to `EVP_cleanup'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x335): undefined reference to `CRYPTO_cleanup_all_ex_data'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x33a): undefined reference to `ERR_free_strings'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_end':
(.text+0x33f): undefined reference to `CONF_modules_free'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `ma_tls_init':
(.text+0x3c1): undefined reference to `SSLv23_client_method'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/libmariadbclient.a(openssl.c.o): In function `my_cb_threadid':
(.text+0x1e): undefined reference to `CRYPTO_THREADID_set_numeric'

I managed to fix it by changing "-lmariadbclient" to: "-lmariadb". After that I was able to compile my program with no errors. I'm not sure if this solution will work for everyone, but worth to try :)

My final Makefile is:

g++ -std=c++11 *.cpp ../common/*.cpp ../common/*.c -o myprogram -I.. -ldl -Wstack-protector -fstack-protector-all -pthread -ggdb -lmariadb -Wwrite-strings -lssl -lcrypto -lz -fPIC

Good luck!


问:
How to scale the image along X and Y axis and crop to a specific height and width?
I need to the stretch the images in X and Y directions but at the same time keep the target image size 300x300. I am using Open CV. Everytime I scale the image and then resize it, I lose the scaling and it looks the same as the image I fed it to scale. How do I accomplish this?

This is the code for scaling

```<code>def scale(infile,outfile,scx,scy):
    img = cv2.imread(infile,0)
    height, width = img.shape[:2]
    #aspectRatio = width / height
    rows,cols = img.shape
    if scx > 1 or scy > 1:
        scimg = cv2.resize(img,None, fx = scx, fy = scy, interpolation = cv2.INTER_LINEAR)
    else:
        scimg = cv2.resize(img,None, fx = scx, fy = scy, interpolation = cv2.INTER_CUBIC)

    #cheight, cwidth = scimg.shape[:2]
    #area = cheight * cwidth
    #nheight = math.sqrt(area / aspectRatio)
    #nwidth = nheight * aspectRatio
    #cv2.resize(scimg,((int)(nwidth), (int)(nheight)), interpolation = cv2.INTER_CUBIC)
    #top = (int) (0.2*rows)
    #bottom = (int) (0.2*rows)
    #left = (int) (0.2*cols)
    #right = (int) (0.2*cols);
    #cv2.copyMakeBorder(scimg,top,left,bottom,right,cv2.BORDER_CONSTANT,value=255)
    cv2.imwrite(outfile,scimg)
</code>```

and I use the scales array for x and y scale factors : scales = [(1,2),(2,1)]
I want that the final image should be 300x300 and should contain the scaled version of the image.
Thank you!!

答:
If you want this just for display purposes, the easiest way is to use cv2.imshow() on your cropped image and use cv2.resizeWindow() to set the window size to the original image size.

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

img = cv2.imread('lena.png')
h, w = img.shape[:2]
scale = (0.6, 0.4) # define your scale
scaled_img = cv2.resize(img, None, fx=scale[0], fy=scale[1]) # scale image

cv2.namedWindow("Scaled image", cv2.WINDOW_NORMAL) # create a resizeable window
cv2.imshow("Scaled image", scaled_img) # display the image in the window
cv2.resizeWindow("Scaled image", w, h) # resize the window
cv2.waitKey(0)
</code>```

Will display a scaled image inside the window where the window has the original image size. This will work even if you scale the image larger, by cropping the right side and top side of the image off (the image is anchored at the bottom left corner of the window). See the output window:

If, however, you want this to be saved into another matrix, then you'll need to pad the image with whatever color you want outside of the image. The easiest way is to create a matrix with that color, but then create an ROI the size of your scaled image and place the scaled image within the ROI.

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

img = cv2.imread('lena.png')
scale = (0.6, 0.4) # define your scale
scaled_img = cv2.resize(img, None, fx=scale[0], fy=scale[1]) # scale image

sh, sw = scaled_img.shape[:2] # get h, w of scaled image
padded_scaled = np.zeros(img.shape, dtype=np.uint8)
padded_scaled[0:sh, 0:sw] = scaled_img

cv2.imshow("Scaled image", padded_scaled)
cv2.waitKey(0)
</code>```

This will put the scaled image at 0,0 in the destination padded_scaled:

If instead you want it displayed at the center, you can do some simple computations to get the center of the image, and then shift by half the width and height of the scaled image for the starting position.

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

img = cv2.imread('lena.png')
scale = (0.6, 0.4) # define your scale
scaled_img = cv2.resize(img, None, fx=scale[0], fy=scale[1]) # scale image

h, w = img.shape[:2] # get h, w of image
sh, sw = scaled_img.shape[:2] # get h, w of scaled image
center_y = int(h/2 - sh/2)
center_x = int(w/2 - sw/2)
padded_scaled = np.zeros(img.shape, dtype=np.uint8) # using img.shape to obtain #channels
padded_scaled[center_y:center_y+sh, center_x:center_x+sw] = scaled_img

cv2.imshow("Scaled image", padded_scaled)
cv2.waitKey(0)
</code>```

This will place the scaled image in the center of the padded matrix:

This will only work when images are scaled smaller than the original image, as you're placing a smaller image into a larger blank matrix. However, if you want to allow for larger scaling, then you'll need a crop at that point. You can just crop a region from the scaled image that is the same size as the original image. However, if the scale is larger than 1 in one dimension and less than 1 in another, you'll need to both crop and pad. I separated this into two sections of if statements: first create a result that is at most the size of the image by cropping if necessary, and then pad if it's smaller.

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

img = cv2.imread('lena.png')
scale_x, scale_y = 13, .3 # define your scale
h, w = img.shape[:2] # get h, w of image

if scale_x > 1 or scale_y > 1:

    scaled_img = cv2.resize(img, None, fx=scale_x, fy=scale_y, interpolation = cv2.INTER_LINEAR) # scale image
    sh, sw = scaled_img.shape[:2] # get h, w of scaled image
    center_y = int(sh/2 - h/2)
    center_x = int(sw/2 - w/2)
    cropped = scaled_img[center_y:center_y+h, center_x:center_x+w]

    result = cropped

elif scale_x > 0 or scale_y > 0:
    scaled_img = cv2.resize(img, None, fx=scale_x, fy=scale_y, interpolation = cv2.INTER_CUBIC) # scale image
    result = scaled_img

else: # scale_x or scale_y is negative
    print("Scales must be greater than 0; returning the original image.")
    result = img

if result.shape < img.shape: # one of the dimensions was scaled smaller, so need to pad
    sh, sw = result.shape[:2] # get h, w of cropped, scaled image
    center_y = int(h/2 - sh/2)
    center_x = int(w/2 - sw/2)
    padded_scaled = np.zeros(img.shape, dtype=np.uint8)
    padded_scaled[center_y:center_y+sh, center_x:center_x+sw] = result
    result = padded_scaled

cv2.imshow("Scaled padded/cropped image", result)
cv2.waitKey(0)
</code>```

With a large stretch in one direction and a smaller scale in the other, this will result in an image displayed like this:

Body:
I need to the stretch the images in X and Y directions but at the same time keep the target image size 300x300. I am using Open CV. Everytime I scale the image and then resize it, I lose the scaling and it looks the same as the image I fed it to scale. How do I accomplish this?

This is the code for scaling

def scale(infile,outfile,scx,scy):
    img = cv2.imread(infile,0)
    height, width = img.shape[:2]
    #aspectRatio = width / height
    rows,cols = img.shape
    if scx > 1 or scy > 1:
        scimg = cv2.resize(img,None, fx = scx, fy = scy, interpolation = cv2.INTER_LINEAR)
    else:
        scimg = cv2.resize(img,None, fx = scx, fy = scy, interpolation = cv2.INTER_CUBIC)

    #cheight, cwidth = scimg.shape[:2]
    #area = cheight * cwidth
    #nheight = math.sqrt(area / aspectRatio)
    #nwidth = nheight * aspectRatio
    #cv2.resize(scimg,((int)(nwidth), (int)(nheight)), interpolation = cv2.INTER_CUBIC)
    #top = (int) (0.2*rows)
    #bottom = (int) (0.2*rows)
    #left = (int) (0.2*cols)
    #right = (int) (0.2*cols);
    #cv2.copyMakeBorder(scimg,top,left,bottom,right,cv2.BORDER_CONSTANT,value=255)
    cv2.imwrite(outfile,scimg)

and I use the scales array for x and y scale factors : scales = [(1,2),(2,1)]
I want that the final image should be 300x300 and should contain the scaled version of the image.
Thank you!!

Body:
If you want this just for display purposes, the easiest way is to use cv2.imshow() on your cropped image and use cv2.resizeWindow() to set the window size to the original image size.

import cv2
import numpy as np

img = cv2.imread('lena.png')
h, w = img.shape[:2]
scale = (0.6, 0.4) # define your scale
scaled_img = cv2.resize(img, None, fx=scale[0], fy=scale[1]) # scale image

cv2.namedWindow("Scaled image", cv2.WINDOW_NORMAL) # create a resizeable window
cv2.imshow("Scaled image", scaled_img) # display the image in the window
cv2.resizeWindow("Scaled image", w, h) # resize the window
cv2.waitKey(0)

Will display a scaled image inside the window where the window has the original image size. This will work even if you scale the image larger, by cropping the right side and top side of the image off (the image is anchored at the bottom left corner of the window). See the output window:

If, however, you want this to be saved into another matrix, then you'll need to pad the image with whatever color you want outside of the image. The easiest way is to create a matrix with that color, but then create an ROI the size of your scaled image and place the scaled image within the ROI.

import cv2
import numpy as np

img = cv2.imread('lena.png')
scale = (0.6, 0.4) # define your scale
scaled_img = cv2.resize(img, None, fx=scale[0], fy=scale[1]) # scale image

sh, sw = scaled_img.shape[:2] # get h, w of scaled image
padded_scaled = np.zeros(img.shape, dtype=np.uint8)
padded_scaled[0:sh, 0:sw] = scaled_img

cv2.imshow("Scaled image", padded_scaled)
cv2.waitKey(0)

This will put the scaled image at 0,0 in the destination padded_scaled:

If instead you want it displayed at the center, you can do some simple computations to get the center of the image, and then shift by half the width and height of the scaled image for the starting position.

import cv2
import numpy as np

img = cv2.imread('lena.png')
scale = (0.6, 0.4) # define your scale
scaled_img = cv2.resize(img, None, fx=scale[0], fy=scale[1]) # scale image

h, w = img.shape[:2] # get h, w of image
sh, sw = scaled_img.shape[:2] # get h, w of scaled image
center_y = int(h/2 - sh/2)
center_x = int(w/2 - sw/2)
padded_scaled = np.zeros(img.shape, dtype=np.uint8) # using img.shape to obtain #channels
padded_scaled[center_y:center_y+sh, center_x:center_x+sw] = scaled_img

cv2.imshow("Scaled image", padded_scaled)
cv2.waitKey(0)

This will place the scaled image in the center of the padded matrix:

This will only work when images are scaled smaller than the original image, as you're placing a smaller image into a larger blank matrix. However, if you want to allow for larger scaling, then you'll need a crop at that point. You can just crop a region from the scaled image that is the same size as the original image. However, if the scale is larger than 1 in one dimension and less than 1 in another, you'll need to both crop and pad. I separated this into two sections of if statements: first create a result that is at most the size of the image by cropping if necessary, and then pad if it's smaller.

import cv2
import numpy as np

img = cv2.imread('lena.png')
scale_x, scale_y = 13, .3 # define your scale
h, w = img.shape[:2] # get h, w of image

if scale_x > 1 or scale_y > 1:

    scaled_img = cv2.resize(img, None, fx=scale_x, fy=scale_y, interpolation = cv2.INTER_LINEAR) # scale image
    sh, sw = scaled_img.shape[:2] # get h, w of scaled image
    center_y = int(sh/2 - h/2)
    center_x = int(sw/2 - w/2)
    cropped = scaled_img[center_y:center_y+h, center_x:center_x+w]

    result = cropped

elif scale_x > 0 or scale_y > 0:
    scaled_img = cv2.resize(img, None, fx=scale_x, fy=scale_y, interpolation = cv2.INTER_CUBIC) # scale image
    result = scaled_img

else: # scale_x or scale_y is negative
    print("Scales must be greater than 0; returning the original image.")
    result = img

if result.shape < img.shape: # one of the dimensions was scaled smaller, so need to pad
    sh, sw = result.shape[:2] # get h, w of cropped, scaled image
    center_y = int(h/2 - sh/2)
    center_x = int(w/2 - sw/2)
    padded_scaled = np.zeros(img.shape, dtype=np.uint8)
    padded_scaled[center_y:center_y+sh, center_x:center_x+sw] = result
    result = padded_scaled

cv2.imshow("Scaled padded/cropped image", result)
cv2.waitKey(0)

With a large stretch in one direction and a smaller scale in the other, this will result in an image displayed like this:


问:
Getting Empty response while fetching JSON data
When I try to fetch JSON data from a website I can see the data in my browser but when i try to do the same through programing i get empty response http://dotsyndicate.com/unionsports/procedure.php?gc=fb1113&getMatches=1 this is the url i am trying to fetch i get empty response in my App where as just changing the value in the url string from 1113 to 1416 the JSON data is properly seen.
 Below is my code

```<code>protected Void doInBackground(Void... params) {
String matchesUrl = "http://dotsyndicate.com/unionsports/procedure.php?gc=fb1113&getMatches=1"
            data = new ArrayList<ListGroup>();
            HttpHandler sh = new HttpHandler();
            String jsonStr = sh.makeServiceCall(matchesUrl);
            Log.e(TAG, "Response from url: " + jsonStr);
            if (jsonStr != null||jsonStr !="") {
                data = jsonExtractor.extractJson(jsonStr);
            }else{
                Log.e(TAG, "Response from url: null");
            }
            return null;
        }
</code>```

HttpHandler class:

```<code>public class HttpHandler {

    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }
}
</code>```

Response from URL:http://dotsyndicate.com/unionsports/procedure.php?gc=fb1113&getMatches=1 inside the app

```<code>E/FootBallMainFragment: Json Data is downloading
06-06 16:06:03.420 23817-24720/com.dotsyndicate.al_islah I/System.out: *** url=http://dotsyndicate.com/unionsports/procedure.php?gc=fb1113&getMatches=1
06-06 16:06:03.420 23817-24720/com.dotsyndicate.al_islah I/System.out: [CDS]rx timeout:0
06-06 16:06:03.421 23817-24720/com.dotsyndicate.al_islah I/System.out: [OkHttp] sendRequest>>
06-06 16:06:03.421 23817-24720/com.dotsyndicate.al_islah I/System.out: [OkHttp] sendRequest<<
06-06 16:06:03.851 23817-24720/com.dotsyndicate.al_islah E/FootBallMainFragment: Response from url:
06-06 16:06:03.870 23817-23817/com.dotsyndicate.al_islah D/ColorDrawable: Color = -1118482, canvas = android.view.GLES20RecordingCanvas@4422f0f, mTintMode = SRC_IN, mTint = null, ColorDrawable = android.graphics.drawable.ColorDrawable@36589616
06-06 16:06:03.871 23817-23817/com.dotsyndicate.al_islah D/ColorDrawable: Color = -13619152, canvas = android.view.GLES20RecordingCanvas@c76cb97, mTintMode = SRC_IN, mTint = null, ColorDrawable = android.graphics.drawable.ColorDrawable@17401d0b
</code>```

Response from URL:http://dotsyndicate.com/unionsports/procedure.php?gc=fb1416&getMatches=1 inside the app

```<code>E/FootBallMainFragment: Json Data is downloading
06-06 16:04:55.988 23817-24044/com.dotsyndicate.al_islah I/System.out: *** url=http://dotsyndicate.com/unionsports/procedure.php?gc=fb17&getMatches=1
06-06 16:04:55.994 23817-24044/com.dotsyndicate.al_islah I/System.out: [CDS]rx timeout:0
06-06 16:04:55.996 23817-24044/com.dotsyndicate.al_islah I/System.out: [OkHttp] sendRequest>>
06-06 16:04:55.999 23817-24044/com.dotsyndicate.al_islah I/System.out: [OkHttp] sendRequest<<
06-06 16:04:56.386 23817-24044/com.dotsyndicate.al_islah E/FootBallMainFragment: Response from url: {"2017-06-08":{"11|2:1|4:1|0":"REAL MADRID|ZERU|23:30|0|0","12|6:2|8:2|0":"AL AHLY|JUVENTUS|23:55|0|0"},"2017-06-07":{"9|1:1|3:1|0":"ATHLETICO|JEMTEM|23:30|0|0","10|5:2|7:2|0":"PREDATORS|JB|23:55|0|0"},"2017-06-06":{"8|6:2|7:2|0":"AL AHLY|JB|23:55|0|0","7|2:1|3:1|0":"REAL MADRID|JEMTEM|23:30|0|0"},"2017-06-01":{"6|8:2|5:2|0":"JUVENTUS|PREDATORS|23:55|0|0","5|4:1|1:1|0":"ZERU|ATHLETICO|23:30|0|0"},"2017-05-31":{"4|7:2|8:2|0":"JB|JUVENTUS|23:55|0|0","3|3:1|4:1|0":"JEMTEM|ZERU|23:30|0|0"},"2017-05-30":{"2|5:2|6:2|0":"PREDATORS|AL AHLY|23:55|0|0","1|1:1|2:1|0":"ATHLETICO|REAL MADRID|23:30|0|0"}}
</code>```

Its bit confusing as both the url are responding correctly but only one works inside the App. Can't figure out why is it so

答:
Finally figured out the problem.

Issue is from the server side. At the time requesting from the user using HttpURLConnection, it sends null useragent and thats the reason server is not responding correctly.
just by adding custom useragent after initializing HttpURLConnection solves the issue.

```<code>conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.71");
</code>```

Body:
When I try to fetch JSON data from a website I can see the data in my browser but when i try to do the same through programing i get empty response http://dotsyndicate.com/unionsports/procedure.php?gc=fb1113&getMatches=1 this is the url i am trying to fetch i get empty response in my App where as just changing the value in the url string from 1113 to 1416 the JSON data is properly seen.
 Below is my code

protected Void doInBackground(Void... params) {
String matchesUrl = "http://dotsyndicate.com/unionsports/procedure.php?gc=fb1113&getMatches=1"
            data = new ArrayList<ListGroup>();
            HttpHandler sh = new HttpHandler();
            String jsonStr = sh.makeServiceCall(matchesUrl);
            Log.e(TAG, "Response from url: " + jsonStr);
            if (jsonStr != null||jsonStr !="") {
                data = jsonExtractor.extractJson(jsonStr);
            }else{
                Log.e(TAG, "Response from url: null");
            }
            return null;
        }

HttpHandler class:

public class HttpHandler {

    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }
}

Response from URL:http://dotsyndicate.com/unionsports/procedure.php?gc=fb1113&getMatches=1 inside the app

E/FootBallMainFragment: Json Data is downloading
06-06 16:06:03.420 23817-24720/com.dotsyndicate.al_islah I/System.out: *** url=http://dotsyndicate.com/unionsports/procedure.php?gc=fb1113&getMatches=1
06-06 16:06:03.420 23817-24720/com.dotsyndicate.al_islah I/System.out: [CDS]rx timeout:0
06-06 16:06:03.421 23817-24720/com.dotsyndicate.al_islah I/System.out: [OkHttp] sendRequest>>
06-06 16:06:03.421 23817-24720/com.dotsyndicate.al_islah I/System.out: [OkHttp] sendRequest<<
06-06 16:06:03.851 23817-24720/com.dotsyndicate.al_islah E/FootBallMainFragment: Response from url:
06-06 16:06:03.870 23817-23817/com.dotsyndicate.al_islah D/ColorDrawable: Color = -1118482, canvas = android.view.GLES20RecordingCanvas@4422f0f, mTintMode = SRC_IN, mTint = null, ColorDrawable = android.graphics.drawable.ColorDrawable@36589616
06-06 16:06:03.871 23817-23817/com.dotsyndicate.al_islah D/ColorDrawable: Color = -13619152, canvas = android.view.GLES20RecordingCanvas@c76cb97, mTintMode = SRC_IN, mTint = null, ColorDrawable = android.graphics.drawable.ColorDrawable@17401d0b

Response from URL:http://dotsyndicate.com/unionsports/procedure.php?gc=fb1416&getMatches=1 inside the app

E/FootBallMainFragment: Json Data is downloading
06-06 16:04:55.988 23817-24044/com.dotsyndicate.al_islah I/System.out: *** url=http://dotsyndicate.com/unionsports/procedure.php?gc=fb17&getMatches=1
06-06 16:04:55.994 23817-24044/com.dotsyndicate.al_islah I/System.out: [CDS]rx timeout:0
06-06 16:04:55.996 23817-24044/com.dotsyndicate.al_islah I/System.out: [OkHttp] sendRequest>>
06-06 16:04:55.999 23817-24044/com.dotsyndicate.al_islah I/System.out: [OkHttp] sendRequest<<
06-06 16:04:56.386 23817-24044/com.dotsyndicate.al_islah E/FootBallMainFragment: Response from url: {"2017-06-08":{"11|2:1|4:1|0":"REAL MADRID|ZERU|23:30|0|0","12|6:2|8:2|0":"AL AHLY|JUVENTUS|23:55|0|0"},"2017-06-07":{"9|1:1|3:1|0":"ATHLETICO|JEMTEM|23:30|0|0","10|5:2|7:2|0":"PREDATORS|JB|23:55|0|0"},"2017-06-06":{"8|6:2|7:2|0":"AL AHLY|JB|23:55|0|0","7|2:1|3:1|0":"REAL MADRID|JEMTEM|23:30|0|0"},"2017-06-01":{"6|8:2|5:2|0":"JUVENTUS|PREDATORS|23:55|0|0","5|4:1|1:1|0":"ZERU|ATHLETICO|23:30|0|0"},"2017-05-31":{"4|7:2|8:2|0":"JB|JUVENTUS|23:55|0|0","3|3:1|4:1|0":"JEMTEM|ZERU|23:30|0|0"},"2017-05-30":{"2|5:2|6:2|0":"PREDATORS|AL AHLY|23:55|0|0","1|1:1|2:1|0":"ATHLETICO|REAL MADRID|23:30|0|0"}}

Its bit confusing as both the url are responding correctly but only one works inside the App. Can't figure out why is it so

Body:
Finally figured out the problem.

Issue is from the server side. At the time requesting from the user using HttpURLConnection, it sends null useragent and thats the reason server is not responding correctly.
just by adding custom useragent after initializing HttpURLConnection solves the issue.

conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.71");


问:
Extract images from PDF without resampling, in python?
How might one extract all images from a pdf document, at native resolution and format? (Meaning extract tiff as tiff, jpeg as jpeg, etc. and without resampling). Layout is unimportant, I don't care were the source image is located on the page.

I'm using python 2.7 but can use 3.x if required.

答:
After some searching I found the following script which works really well with my PDF's. It does only tackle JPG, but it worked perfectly with my unprotected files. Also is does not require any outside libraries.

Not to take any credit, the script originates from Ned Batchelder, and not me.
Python3 code: extract jpg's from pdf's. Quick and dirty

```<code>import sys

with open(sys.argv[1],"rb") as file:
    file.seek(0)
    pdf = file.read()

startmark = b"\xff\xd8"
startfix = 0
endmark = b"\xff\xd9"
endfix = 2
i = 0

njpg = 0
while True:
    istream = pdf.find(b"stream", i)
    if istream < 0:
        break
    istart = pdf.find(startmark, istream, istream + 20)
    if istart < 0:
        i = istream + 20
        continue
    iend = pdf.find(b"endstream", istart)
    if iend < 0:
        raise Exception("Didn't find end of stream!")
    iend = pdf.find(endmark, iend - 20)
    if iend < 0:
        raise Exception("Didn't find end of JPG!")

    istart += startfix
    iend += endfix
    print("JPG %d from %d to %d" % (njpg, istart, iend))
    jpg = pdf[istart:iend]
    with open("jpg%d.jpg" % njpg, "wb") as jpgfile:
        jpgfile.write(jpg)

    njpg += 1
    i = iend
</code>```

Body:
After some searching I found the following script which works really well with my PDF's. It does only tackle JPG, but it worked perfectly with my unprotected files. Also is does not require any outside libraries.

Not to take any credit, the script originates from Ned Batchelder, and not me.
Python3 code: extract jpg's from pdf's. Quick and dirty

import sys

with open(sys.argv[1],"rb") as file:
    file.seek(0)
    pdf = file.read()

startmark = b"\xff\xd8"
startfix = 0
endmark = b"\xff\xd9"
endfix = 2
i = 0

njpg = 0
while True:
    istream = pdf.find(b"stream", i)
    if istream < 0:
        break
    istart = pdf.find(startmark, istream, istream + 20)
    if istart < 0:
        i = istream + 20
        continue
    iend = pdf.find(b"endstream", istart)
    if iend < 0:
        raise Exception("Didn't find end of stream!")
    iend = pdf.find(endmark, iend - 20)
    if iend < 0:
        raise Exception("Didn't find end of JPG!")

    istart += startfix
    iend += endfix
    print("JPG %d from %d to %d" % (njpg, istart, iend))
    jpg = pdf[istart:iend]
    with open("jpg%d.jpg" % njpg, "wb") as jpgfile:
        jpgfile.write(jpg)

    njpg += 1
    i = iend


问:
vs2010 unable to connect to the ASP.net development server
i am getting this error while trying to view in browser. i checked the host file and the 127.0.0.1       localhost line wasn't commented

i am on windows server 2003 and my IIS is working fine as projects on VS2008 are working fine

i am really confused and trapped in this.

答:
Right-click the project and check Properties -> Web.

Personally I've found the most reliable way to set-up is to select 'Use Custom Web Server' and put a valid local URL in there (e.g. http://MyTestWebApp.local)

You'll also need to map this url to localhost (127.0.0.1) in your hosts file and make the neccessary changes to the bindings for the site in IIS.

Good luck.

ContentLicense: CC BY-SA 2.5


问:
Using Training TFRecords that are stored on Google Cloud
My goal is to use training data (format: tfrecords) stored on Google Cloud storage when I run my Tensorflow Training App, locally. (Why locally? : I am testing before I turn it into a training package for Cloud ML)

Based on this thread I shouldn't have to do anything since the underlying Tensorflow API's should be able to read a gs://(url)

However thats not the case and the errors I see are of the format:

2017-06-06 15:38:55.589068: I
tensorflow/core/platform/cloud/retrying_utils.cc:77] The operation
failed and will be automatically retried in 1.38118 seconds (attempt 1
out of 10), caused by: Unavailable: Error executing an HTTP request
(HTTP response code 0, error code 6, error message 'Couldn't resolve
host 'metadata'')

2017-06-06 15:38:56.976396: I
tensorflow/core/platform/cloud/retrying_utils.cc:77] The operation
failed and will be automatically retried in 1.94469 seconds (attempt 2
out of 10), caused by: Unavailable: Error executing an HTTP request
(HTTP response code 0, error code 6, error message 'Couldn't resolve
host 'metadata'')

2017-06-06 15:38:58.925964: I
tensorflow/core/platform/cloud/retrying_utils.cc:77] The operation
failed and will be automatically retried in 2.76491 seconds (attempt 3
out of 10), caused by: Unavailable: Error executing an HTTP request
(HTTP response code 0, error code 6, error message 'Couldn't resolve
host 'metadata'')

I'm not able to follow where I have to begin debugging this error.

Here is a snippet that reproduced the problem and also shows the tensorflow API's that I am using.

```<code>def _preprocess_features(features):
        """Function that returns preprocessed images"""

def _parse_single_example_from_tfrecord(value):
    features = (
        tf.parse_single_example(value,
                                features={'image_raw': tf.FixedLenFeature([], tf.string),
                                          'label': tf.FixedLenFeature([model_config.LABEL_SIZE], tf.int64)
                                          })
        )
    return features

def _read_and_decode_tfrecords(filename_queue):
    reader = tf.TFRecordReader()
    # Point it at the filename_queue
    _, value = reader.read(filename_queue)
    features = _parse_single_example_from_tfrecord(value)
    # decode the binary string image data
    image, label = _preprocess_features(features)
    return image, label

def test_tfread(filelist):
  train_filename_queue = (
    tf.train.string_input_producer(filelist,
                                   num_epochs=None,
                                   shuffle=True))
  image, label = (
    _read_and_decode_tfrecords(train_filename_queue))
  return image

images= test_tfread(["gs://test-bucket/t.tfrecords"])
sess = tf.Session(config=tf.ConfigProto(
                allow_soft_placement=True,
                log_device_placement=True))
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
try:
  for step in range(model_config.MAX_STEPS):
      _ = sess.run([images])
finally:
  # When done, ask the threads to stop.
  coord.request_stop()
# Finally, wait for them to join (i.e. cleanly shut down)
coord.join(threads)
</code>```

答:
Try executing the following command

gcloud auth application-default login

Body:
My goal is to use training data (format: tfrecords) stored on Google Cloud storage when I run my Tensorflow Training App, locally. (Why locally? : I am testing before I turn it into a training package for Cloud ML)

Based on this thread I shouldn't have to do anything since the underlying Tensorflow API's should be able to read a gs://(url)

However thats not the case and the errors I see are of the format:

2017-06-06 15:38:55.589068: I
tensorflow/core/platform/cloud/retrying_utils.cc:77] The operation
failed and will be automatically retried in 1.38118 seconds (attempt 1
out of 10), caused by: Unavailable: Error executing an HTTP request
(HTTP response code 0, error code 6, error message 'Couldn't resolve
host 'metadata'')

2017-06-06 15:38:56.976396: I
tensorflow/core/platform/cloud/retrying_utils.cc:77] The operation
failed and will be automatically retried in 1.94469 seconds (attempt 2
out of 10), caused by: Unavailable: Error executing an HTTP request
(HTTP response code 0, error code 6, error message 'Couldn't resolve
host 'metadata'')

2017-06-06 15:38:58.925964: I
tensorflow/core/platform/cloud/retrying_utils.cc:77] The operation
failed and will be automatically retried in 2.76491 seconds (attempt 3
out of 10), caused by: Unavailable: Error executing an HTTP request
(HTTP response code 0, error code 6, error message 'Couldn't resolve
host 'metadata'')

I'm not able to follow where I have to begin debugging this error.

Here is a snippet that reproduced the problem and also shows the tensorflow API's that I am using.

def _preprocess_features(features):
        """Function that returns preprocessed images"""

def _parse_single_example_from_tfrecord(value):
    features = (
        tf.parse_single_example(value,
                                features={'image_raw': tf.FixedLenFeature([], tf.string),
                                          'label': tf.FixedLenFeature([model_config.LABEL_SIZE], tf.int64)
                                          })
        )
    return features

def _read_and_decode_tfrecords(filename_queue):
    reader = tf.TFRecordReader()
    # Point it at the filename_queue
    _, value = reader.read(filename_queue)
    features = _parse_single_example_from_tfrecord(value)
    # decode the binary string image data
    image, label = _preprocess_features(features)
    return image, label

def test_tfread(filelist):
  train_filename_queue = (
    tf.train.string_input_producer(filelist,
                                   num_epochs=None,
                                   shuffle=True))
  image, label = (
    _read_and_decode_tfrecords(train_filename_queue))
  return image

images= test_tfread(["gs://test-bucket/t.tfrecords"])
sess = tf.Session(config=tf.ConfigProto(
                allow_soft_placement=True,
                log_device_placement=True))
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
try:
  for step in range(model_config.MAX_STEPS):
      _ = sess.run([images])
finally:
  # When done, ask the threads to stop.
  coord.request_stop()
# Finally, wait for them to join (i.e. cleanly shut down)
coord.join(threads)


问:
Graph API not listing all groups by default
I'm trying to figure out a correct way to list our Office 365 groups that have Microsoft Teams linked to them.

However, when I run this request, it's not returning all of our O365 groups:
https://graph.microsoft.com/v1.0/groups

Then again, this request will return all of the groups:
https://graph.microsoft.com/v1.0/groups?$orderby=displayName

Finally, if I try searching for the groups in PowerShell, this happens:

Get-AzureADGroup (with Azure Active Directory PowerShell Version 2)

NOT OK - Only some groups returned

Get-MsolGroup (with Azure Active Directory PowerShell Version 1)

OK - All groups returned

Get-AzureADGroup -ObjectId

Using the ID found with Get-MsolGroup

OK - The group is found even though it was not in the list of all groups

So I have to say I'm a bit confused. Any idea of what's going on? What's the request I should use in Graph API to list (and potentially update) all O365 groups?

答:
https://graph.microsoft.com/beta/me/joinedTeams will return all the Teams-enabled groups I'm a member of. See this topic.

There's no API currently that will list all Teams-enabled groups in the tenant.  Do you have a scenario for why you are looking for this API?  This could be something we add in the future.

Hope this helps,


问:
Fastest way to sort 10 numbers? (numbers are 32 bit)
I'm solving a problem and it involves sorting 10 numbers (int32) very quickly. My application needs to sort 10 numbers millions of times as fast as possible. I'm sampling a data set of billions of elements and every time I need to pick 10 numbers out of it (simplified) and sort them (and make conclusions from the sorted 10 element list).

Currently I'm using insertion sort, but I imagine I could implement a very fast custom sorting algorithm for my specific problem of 10 numbers which would beat insertion sort.

How can I approach this problem?

答:
For reasons similar to those that I described here, the following sorting functions, sort6_iterator() and sort10_iterator_local(), should perform well, where the sorting network was taken from here:

```<code>template<class IterType>
inline void sort10_iterator(IterType it)
{
#define SORT2(x,y) {if(data##x>data##y)std::swap(data##x,data##y);}
#define DD1(a)   auto data##a=*(data+a);
#define DD2(a,b) auto data##a=*(data+a), data##b=*(data+b);
#define CB1(a)   *(data+a)=data##a;
#define CB2(a,b) *(data+a)=data##a;*(data+b)=data##b;
  DD2(1,4) SORT2(1,4) DD2(7,8) SORT2(7,8) DD2(2,3) SORT2(2,3) DD2(5,6) SORT2(5,6) DD2(0,9) SORT2(0,9)
  SORT2(2,5) SORT2(0,7) SORT2(8,9) SORT2(3,6)
  SORT2(4,9) SORT2(0,1)
  SORT2(0,2) CB1(0) SORT2(6,9) CB1(9) SORT2(3,5) SORT2(4,7) SORT2(1,8)
  SORT2(3,4) SORT2(5,8) SORT2(6,7) SORT2(1,2)
  SORT2(7,8) CB1(8) SORT2(1,3) CB1(1) SORT2(2,5) SORT2(4,6)
  SORT2(2,3) CB1(2) SORT2(6,7) CB1(7) SORT2(4,5)
  SORT2(3,4) CB2(3,4) SORT2(5,6) CB2(5,6)
#undef CB1
#undef CB2
#undef DD1
#undef DD2
#undef SORT2
}
</code>```

To call this function I passed it a std::vector iterator.

Body:
For reasons similar to those that I described here, the following sorting functions, sort6_iterator() and sort10_iterator_local(), should perform well, where the sorting network was taken from here:

template<class IterType>
inline void sort10_iterator(IterType it)
{
#define SORT2(x,y) {if(data##x>data##y)std::swap(data##x,data##y);}
#define DD1(a)   auto data##a=*(data+a);
#define DD2(a,b) auto data##a=*(data+a), data##b=*(data+b);
#define CB1(a)   *(data+a)=data##a;
#define CB2(a,b) *(data+a)=data##a;*(data+b)=data##b;
  DD2(1,4) SORT2(1,4) DD2(7,8) SORT2(7,8) DD2(2,3) SORT2(2,3) DD2(5,6) SORT2(5,6) DD2(0,9) SORT2(0,9)
  SORT2(2,5) SORT2(0,7) SORT2(8,9) SORT2(3,6)
  SORT2(4,9) SORT2(0,1)
  SORT2(0,2) CB1(0) SORT2(6,9) CB1(9) SORT2(3,5) SORT2(4,7) SORT2(1,8)
  SORT2(3,4) SORT2(5,8) SORT2(6,7) SORT2(1,2)
  SORT2(7,8) CB1(8) SORT2(1,3) CB1(1) SORT2(2,5) SORT2(4,6)
  SORT2(2,3) CB1(2) SORT2(6,7) CB1(7) SORT2(4,5)
  SORT2(3,4) CB2(3,4) SORT2(5,6) CB2(5,6)
#undef CB1
#undef CB2
#undef DD1
#undef DD2
#undef SORT2
}

To call this function I passed it a std::vector iterator.


问:
Newline "\n" not Working when Writing a .txt file Python
```<code>for word in keys:
    out.write(word+" "+str(dictionary[word])+"\n")
    out=open("alice2.txt", "r")
    out.read()
</code>```

For some reason, instead of getting a new line for every word in the dictionary, python is literally printing \n between every key and value.
I have even tried to write new line separately, like this...

```<code>for word in keys:
    out.write(word+" "+str(dictionary[word]))
    out.write("\n")
    out=open("alice2.txt", "r")
    out.read()
</code>```

What do I do?

答:
Suppose you do:

```<code>>>> with open('/tmp/file', 'w') as f:
...    for i in range(10):
...       f.write("Line {}\n".format(i))
...
</code>```

And then you do:

```<code>>>> with open('/tmp/file') as f:
...    f.read()
...
'Line 0\nLine 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7\nLine 8\nLine 9\n'
</code>```

It appears that Python has just written the literal \n in the file. It hasn't. Go to the terminal:

```<code>$ cat /tmp/file
Line 0
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
</code>```

The Python interpreter is showing you the invisible \n character. The file is fine (in this case anyway...) The terminal is showing the __repr__ of the string. You can print the string to see the special characters interpreted:

```<code>>>> s='Line 1\n\tLine 2\n\n\t\tLine3'
>>> s
'Line 1\n\tLine 2\n\n\t\tLine3'
>>> print s
Line 1
    Line 2

        Line3
</code>```

Note how I am opening and (automatically) closing a file with with:

```<code>with open(file_name, 'w') as f:
  # do something with a write only file
# file is closed at the end of the block
</code>```

It appears in your example that you are mixing a file open for reading and writing at the same time. You will either confuse yourself or the OS if you do that. Either use open(fn, 'r+') or first write the file, close it, then re-open for reading. It is best to use a with block so the close is automatic.

Body:
for word in keys:
    out.write(word+" "+str(dictionary[word])+"\n")
    out=open("alice2.txt", "r")
    out.read()

For some reason, instead of getting a new line for every word in the dictionary, python is literally printing \n between every key and value.
I have even tried to write new line separately, like this...

for word in keys:
    out.write(word+" "+str(dictionary[word]))
    out.write("\n")
    out=open("alice2.txt", "r")
    out.read()

What do I do?

Body:
Suppose you do:

>>> with open('/tmp/file', 'w') as f:
...    for i in range(10):
...       f.write("Line {}\n".format(i))
...

And then you do:

>>> with open('/tmp/file') as f:
...    f.read()
...
'Line 0\nLine 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7\nLine 8\nLine 9\n'

It appears that Python has just written the literal \n in the file. It hasn't. Go to the terminal:

$ cat /tmp/file
Line 0
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9

The Python interpreter is showing you the invisible \n character. The file is fine (in this case anyway...) The terminal is showing the __repr__ of the string. You can print the string to see the special characters interpreted:

>>> s='Line 1\n\tLine 2\n\n\t\tLine3'
>>> s
'Line 1\n\tLine 2\n\n\t\tLine3'
>>> print s
Line 1
    Line 2

        Line3

Note how I am opening and (automatically) closing a file with with:

with open(file_name, 'w') as f:
  # do something with a write only file
# file is closed at the end of the block

It appears in your example that you are mixing a file open for reading and writing at the same time. You will either confuse yourself or the OS if you do that. Either use open(fn, 'r+') or first write the file, close it, then re-open for reading. It is best to use a with block so the close is automatic.


问:
Eclipse: How do you change the highlight color of the currently selected method/expression?
In eclipse, when your cursor is placed on a method (or other things), other places the method exists are highlighted. I'd like to change the color of this highlight, but after scouring the eclipse preferences many times in all 3 places, I have yet to find it.

Any of you Eclipse gurus know where to find this option?

答:
If you're using eclipse with PHP package and want to change highlighted colour then there is slight difference to above answer.

Right click on highlighted word

Select 'Preferences'

Go to General > Editors > Text Editors > Annotations. Now look for "PHP elements 'read' occurrences" and "PHP elements 'write' occurrences". You can select your desired colour there.


问:
Unable to encode String for URL in Swift 3
I used to develop iOS Apps using Objective-C. Now I have recently migrated to Swift. In my app, I have a button that opens MS Outlook App with the pre-filled Subject and Body.

I did a similar App in Objective-C and used the below code to Encode my String for URL.

```<code>NSString *emailSubject = @"Test Subject";
NSString *encodedSubject = [emailSubject stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
</code>```

Now I am unable to do the same in Swift 3. Below is the code that I tried.

```<code>var subjectText: String = "Test Subject"

var encodedSubject = subjectText.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

var stringURL: String = "ms-outlook://compose?subject=" + subjectText + "&body=TestingEmailNow"
// Convert the string to a URL.
var url = URL(string: stringURL)

// Open the app that responds to the URL scheme (should be Outlook).
UIApplication.shared.openURL(url!)
</code>```

The error that I am getting is below.

fatal error: unexpectedly found nil while unwrapping an Optional value
  2017-06-07 04:29:35.158030+0400 My App[1286:405793] fatal error: unexpectedly found nil while unwrapping an Optional value

I know that this error is coming due to the space in my Subject. I can say this because if I remove the space, I don't even have to encode it. It works directly. What am I doing wrong over here?

答:
Variable used was the problem but I'd also suggest using URLComponents instead of building the URL as string.</p>

```<code>var subjectText: String = "Test Subject"

var components = URLComponents()

components.scheme = "ms-outlook"
components.host = "compose"

components.queryItems = [
    URLQueryItem(name: "subject", value: subjectText),
    URLQueryItem(name: "body", value: "TestingEmailNow")
]

if let url = components.url {
    UIApplication.shared.openURL(url)
}
</code>```

Body:
I used to develop iOS Apps using Objective-C. Now I have recently migrated to Swift. In my app, I have a button that opens MS Outlook App with the pre-filled Subject and Body.

I did a similar App in Objective-C and used the below code to Encode my String for URL.

NSString *emailSubject = @"Test Subject";
NSString *encodedSubject = [emailSubject stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];

Now I am unable to do the same in Swift 3. Below is the code that I tried.

var subjectText: String = "Test Subject"

var encodedSubject = subjectText.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

var stringURL: String = "ms-outlook://compose?subject=" + subjectText + "&body=TestingEmailNow"
// Convert the string to a URL.
var url = URL(string: stringURL)

// Open the app that responds to the URL scheme (should be Outlook).
UIApplication.shared.openURL(url!)

The error that I am getting is below.

fatal error: unexpectedly found nil while unwrapping an Optional value
  2017-06-07 04:29:35.158030+0400 My App[1286:405793] fatal error: unexpectedly found nil while unwrapping an Optional value

I know that this error is coming due to the space in my Subject. I can say this because if I remove the space, I don't even have to encode it. It works directly. What am I doing wrong over here?

Body:
Variable used was the problem but I'd also suggest using URLComponents instead of building the URL as string.

var subjectText: String = "Test Subject"

var components = URLComponents()

components.scheme = "ms-outlook"
components.host = "compose"

components.queryItems = [
    URLQueryItem(name: "subject", value: subjectText),
    URLQueryItem(name: "body", value: "TestingEmailNow")
]

if let url = components.url {
    UIApplication.shared.openURL(url)
}


问:
SOAP interceptor for .NET?
I'm working with an API and my results (CRUD) are getting mangled somehow in the return and .NET is throwing invalid XML errors.  Is there a setup trick to getting tcpmon to work with a debugger in Visual Studio?  Or is there another lightweight interceptor/analyzer that I can use to capture the XML?

Thanks.

答: I use SoapUI to test my web services and it will give more detailed statistics on requests and responses than I've ever imagined.</p>

Title: SOAP interceptor for .NET?


问:
Move user uploaded video from local to amazon S3 in rails app
I have a rails app that lets users upload videos. Right now, it works well locally, I want to move it to AWS so that when a user uploads a video, it gets added to my S3 bucket.

Right now, my video uploader.rb looks like this:

```<code>class VideoUploader < CarrierWave::Uploader::Base

  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

end
</code>```

What do I have to change here so it'll be uploaded to S3?

I have also read a little bit about the FOG gem. From what I understand, it helps you upload videos locally and also on the cloud. Will I have to use it here? Sorry if I'm asking this question the wrong way, I'm new here and also to rails.

Thanks a lot and please let me know if you need any more information.

答:
You can do the following changes to your Ruby code to upload videos and also allowing streaming of videos.

Setup AWS CloudFront with RTMP Distribution for Streaming Videos uploaded to S3.

Use Ruby SDK for Signed URLs to create a Signed URL(Verifying access control) and return the response from a Rails endpoint to the browser, so that using the particular signed URL, the web application running in browser can directly upload the file to S3.

After uploading the file, using AWS CloudFront url, you can stream the video to a video player in browser.

Body:
I have a rails app that lets users upload videos. Right now, it works well locally, I want to move it to AWS so that when a user uploads a video, it gets added to my S3 bucket.

Right now, my video uploader.rb looks like this:

class VideoUploader < CarrierWave::Uploader::Base

  storage :file

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

end

What do I have to change here so it'll be uploaded to S3?

I have also read a little bit about the FOG gem. From what I understand, it helps you upload videos locally and also on the cloud. Will I have to use it here? Sorry if I'm asking this question the wrong way, I'm new here and also to rails.

Thanks a lot and please let me know if you need any more information.


问:
rewrite-rule to properly handle ?-sign
I'm having a annoying issue with rewrite-using cherokee web-server.

I want to convert:

```<code>http://example.com/mypage.phtml?cmd=print
=> to =>
http://example.com/index.php?page=mypage&cmd=print
</code>```

The problem is that the ?-sign messes up the cmd;

```<code>$_GET : array('page'=>'mypage', '?cmd'=>'print')
</code>```

Cherokee is configured with:

```<code>regexp: ^/(.*)\.phtml(.*)$
internal subst: /index.php?page=$1&$2
</code>```

So my question: How to best "eat up" the question-mark if present.

Regards,

//teson

答:
Try matching it explicitly before the capturing parentheses:

```<code>regexp: ^/(.*)\.phtml\??(.*)$
</code>```

\? is a literal ?, and the following ? means "match 0 or 1 times".

Title: rewrite-rule to properly handle ?-sign

Body:
I'm having a annoying issue with rewrite-using cherokee web-server.

I want to convert:

http://example.com/mypage.phtml?cmd=print
=> to =>
http://example.com/index.php?page=mypage&cmd=print

The problem is that the ?-sign messes up the cmd;

$_GET : array('page'=>'mypage', '?cmd'=>'print')

Cherokee is configured with:

regexp: ^/(.*)\.phtml(.*)$
internal subst: /index.php?page=$1&$2

So my question: How to best "eat up" the question-mark if present.

Regards,

//teson

Body:
Try matching it explicitly before the capturing parentheses:

regexp: ^/(.*)\.phtml\??(.*)$

\? is a literal ?, and the following ? means "match 0 or 1 times".


问:
Add element count to end of each line in a file containing sets
I have a file which contains sets of data and I need to add the total amount of lines to each line/record.

File Example:

```<code>set1-open
record
record
record
record
set1-close
set2-open
record
record
record
record
record
set2-close
</code>```

and so on...

I would like to have:

```<code>set1-open
record 4
record 4
record 4
record 4
set1-close
set2-open
record 5
record 5
record 5
record 5
record 5
set2-close
</code>```

I'm writing this in Shell, so sed would be preferred.

答:
This might work for you (GNU sed):

```<code>sed -r '/open/{x;s/.*/0/;x};//,/close/{//b;x;:a;s/9(#*)$/#\1/;ta;s/$/:0123456789/;s/(.)(#*):.*\1(.).*/\3\2/;y/#/0/;x;G;s/\n/ /}' file
</code>```

Clear the hold space (HS) on encountering the start of block of records and prep it with a counter set to zero. Within a block of records use the HS to keep a counter which is incremented and then a copy appended to each record.

Body:
I have a file which contains sets of data and I need to add the total amount of lines to each line/record.

File Example:

set1-open
record
record
record
record
set1-close
set2-open
record
record
record
record
record
set2-close

and so on...

I would like to have:

set1-open
record 4
record 4
record 4
record 4
set1-close
set2-open
record 5
record 5
record 5
record 5
record 5
set2-close

I'm writing this in Shell, so sed would be preferred.

Body:
This might work for you (GNU sed):

sed -r '/open/{x;s/.*/0/;x};//,/close/{//b;x;:a;s/9(#*)$/#\1/;ta;s/$/:0123456789/;s/(.)(#*):.*\1(.).*/\3\2/;y/#/0/;x;G;s/\n/ /}' file

Clear the hold space (HS) on encountering the start of block of records and prep it with a counter set to zero. Within a block of records use the HS to keep a counter which is incremented and then a copy appended to each record.


问:
excel powerpivot update error "object was not found in the cube"
I have an PowerPivot file that pulls data directly from a SQL data warehouse. Next it is fed into pivot tables. When I try and update I get the following error:

Query (20,3916) The level '&[Desktop]' object was not found in the cube when the string, [OfficeFlatFile].TopicLevel2Name]&[Desktop], was parsed.

I checked my data source and found that the member "Desktop" was no longer available (no surprise there). But I can't get the file to update now. I tried updating the PowerPivot data connection first but that didn't work either.

This is the most recent info I could find, and it doesn't help.
https://connect.microsoft.com/SQLServer/feedback/details/756691/powerpivot-data-could-not-be-retrieved-from-the-exteral-data-source

Does anyone know a solution apart from rebuilding the file?

答: Remove the . in column names that are in the join. Reference.


问:
External login verification in Joomla
Using code from simular questions here I am trying to login users from a game into Joomla.
My problem is that i'm not getting a positive pasword verification.

Since I was having great difficult converting my original script what worked prior joomla 3.2 with the solutions given to simular questions, I made this test script.

I created user named 'test' with a pasword 'test' and copied the encrypted pw from phpMyAmdin to the script.
According to all information I can find on Joomla and this website my pasword verification should be succesfull, but its failing.
Am I missing something or what is going on here?

```<code><?php
define( '_JEXEC', 1 );
define('JPATH_BASE', "../public_html" );
define( 'DS', DIRECTORY_SEPARATOR );

require_once ( "instellingen.php" );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );

$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();

// created a test username with test as password in joomla
$username   = "test";
$password   = "test";
$dbPW       = "$P$DxdrgIwlYqFE23mQjYvgvTNO3zoVN40";  // copied from phpMyAdmin
$id         = JUserHelper::getUserId($username);
echo "$id"; //<-- matches value shown in phpMyAdmin

if(JUserHelper::verifyPassword($password, $dbPW, $id))
{
    echo "succesfull Login!";
}
else
{
    echo "failed Login!";
}
?>
</code>```

答:
I did a login page which from outside of Joomla, ( I used Joomla 2.5, if you are using higher version, you can take it as a reference)</p>

```<code><?php

//this xxx.php is outside of Joomla root
//and Joomla root is in ./login folder

define( '_JEXEC', 1 );
define( 'JPATH_BASE', './login' );

// Required Files
require_once (JPATH_BASE . '/includes/defines.php');
require_once (JPATH_BASE . '/includes/framework.php');

// To use Joomla's Database Class
require_once (JPATH_BASE .'/libraries/joomla/factory.php');

/********* POST login data from some where *********/
if(isset($_POST['uname']) && isset($_POST['psw'])) {

    $credentials['username'] = trim($_POST['uname']);
    $credentials['password'] = trim($_POST['psw']);

    if(class_exists(JFactory)) {

        $app = JFactory::getApplication('site');

        // Get a database object
        $db     = JFactory::getDbo();
        $query  = $db->getQuery(true);

        $query->select('id, password');
        $query->from('#__users');
        $query->where('username=' . $db->quote($credentials['username']));

        $db->setQuery($query);
        $result = $db->loadObject();

        if ($result)
        {
            $match = JUserHelper::verifyPassword($credentials['password'], $result->password, $result->id);

            if ($match === true)
            {
                $user = JUser::getInstance($result->id); // Bring this in line with the rest of the system
                $app->login($credentials);

                echo ("This user is logged in and Joomla also logged in! ");
            }
            else
            {
                echo ("User name and password not match! ");
            }
        }
        else
        {
            echo ("THE USER IS NOT REGISTERED! ");
        }
    }
}

?>
</code>```

Title: External login verification in Joomla

Body:
Using code from simular questions here I am trying to login users from a game into Joomla.
My problem is that i'm not getting a positive pasword verification.

Since I was having great difficult converting my original script what worked prior joomla 3.2 with the solutions given to simular questions, I made this test script.

I created user named 'test' with a pasword 'test' and copied the encrypted pw from phpMyAmdin to the script.
According to all information I can find on Joomla and this website my pasword verification should be succesfull, but its failing.
Am I missing something or what is going on here?

<?php
define( '_JEXEC', 1 );
define('JPATH_BASE', "../public_html" );
define( 'DS', DIRECTORY_SEPARATOR );

require_once ( "instellingen.php" );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );

$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();

// created a test username with test as password in joomla
$username   = "test";
$password   = "test";
$dbPW       = "$P$DxdrgIwlYqFE23mQjYvgvTNO3zoVN40";  // copied from phpMyAdmin
$id         = JUserHelper::getUserId($username);
echo "$id"; //<-- matches value shown in phpMyAdmin

if(JUserHelper::verifyPassword($password, $dbPW, $id))
{
    echo "succesfull Login!";
}
else
{
    echo "failed Login!";
}
?>

Body:
I did a login page which from outside of Joomla, ( I used Joomla 2.5, if you are using higher version, you can take it as a reference)

<?php

//this xxx.php is outside of Joomla root
//and Joomla root is in ./login folder

define( '_JEXEC', 1 );
define( 'JPATH_BASE', './login' );

// Required Files
require_once (JPATH_BASE . '/includes/defines.php');
require_once (JPATH_BASE . '/includes/framework.php');

// To use Joomla's Database Class
require_once (JPATH_BASE .'/libraries/joomla/factory.php');

/********* POST login data from some where *********/
if(isset($_POST['uname']) && isset($_POST['psw'])) {

    $credentials['username'] = trim($_POST['uname']);
    $credentials['password'] = trim($_POST['psw']);

    if(class_exists(JFactory)) {

        $app = JFactory::getApplication('site');

        // Get a database object
        $db     = JFactory::getDbo();
        $query  = $db->getQuery(true);

        $query->select('id, password');
        $query->from('#__users');
        $query->where('username=' . $db->quote($credentials['username']));

        $db->setQuery($query);
        $result = $db->loadObject();

        if ($result)
        {
            $match = JUserHelper::verifyPassword($credentials['password'], $result->password, $result->id);

            if ($match === true)
            {
                $user = JUser::getInstance($result->id); // Bring this in line with the rest of the system
                $app->login($credentials);

                echo ("This user is logged in and Joomla also logged in! ");
            }
            else
            {
                echo ("User name and password not match! ");
            }
        }
        else
        {
            echo ("THE USER IS NOT REGISTERED! ");
        }
    }
}

?>


问:
Remove Netmiko Automatic Output
I have a quick question in regards to the Netmiko module (based on the Paramiko module).

I have a for loop that iterates through a bunch of Cisco boxes (around 40)...and once they complete I get the following each time a SSH connection establishes:

SSH connection established to ip address:22

Interactive SSH session established

This isn't in my print statements or anything, it's obviously hard coded within ConnectionHandler (which I use to make the SSH connections).

This output really makes my output muddled and full of 40 extra lines I do not need.  Is there any way I can get these removed from the output?

Regards,

答:
Found this answer out through reddit.

Add the key 'verbose': False to your network device dictionary. More information on the Netmiko Standard Tutorial page

Title: Remove Netmiko Automatic Output