问:
Example code for a working POST in swagger go
What am I doing wrong in this approach?

I try to reimplent an old API, however the go implementation. Basically i try to POST a list of strings to the server. but all i get is an error 500 from the server, whenn i try:

```<code>go run gen/cmd/greeter-server/main.go --port=3000  &
echo '["a","b"]' |  http -v post  :34307/api/greeting/2.0/revisit
</code>```

RESULT

```<code>HTTP/1.1 500 Internal Server Error
Content-Length: 68
Content-Type: application/json
Date: Mon, 06 Mar 2017 17:41:16 GMT

{
    "code": 500,
    "message": "no consumer registered for application/json"
}
</code>```

This is the code i try to implement.

```<code>  api.TrackingRevisitHandler = operations.TrackingRevisitHandlerFunc(
                func(params operations.TrackingRevisitParams) middleware.Responder {

                        list := params.IdList
                        log.Printf("%v\n",list)
                        return operations.NewTrackingRevisitOK().WithPayload("RESULT")
        })
</code>```

I use

```<code>swagger generate server -A greeter -t gen -f ./swagger/swagger.yml
</code>```

to generate the server from this yaml:

```<code>---
swagger: '2.0'
info:
  version: 1.0.0
  title: Greeting Server

basePath: "/api/greeting/2.0"

paths:
  /revisit:
    post:
      produces:
      - application/json
      consumes:
      - application/json
      parameters:
        - name: site
          required: true
          type: string
          in: query
          description: site name

        - name: userlist
          in: body
          description: list of users
          required: true
          schema:
            "$ref": "#/definitions/Userlist"

      operationId: trackingRevisit

      responses:
        200:
          description:  return list of users which need revisit
          schema:
            type: string
</code>```

答:
if you move the consumes and produces up to the top level it will start to work

The other way to make it work it to set up the json consumer. This is a bug in go-swagger.

You can watch this issue: https://github.com/go-swagger/go-swagger/issues/987 for a proper resolution

Body:
What am I doing wrong in this approach?

I try to reimplent an old API, however the go implementation. Basically i try to POST a list of strings to the server. but all i get is an error 500 from the server, whenn i try:

go run gen/cmd/greeter-server/main.go --port=3000  &
echo '["a","b"]' |  http -v post  :34307/api/greeting/2.0/revisit

RESULT

HTTP/1.1 500 Internal Server Error
Content-Length: 68
Content-Type: application/json
Date: Mon, 06 Mar 2017 17:41:16 GMT

{
    "code": 500,
    "message": "no consumer registered for application/json"
}

This is the code i try to implement.

  api.TrackingRevisitHandler = operations.TrackingRevisitHandlerFunc(
                func(params operations.TrackingRevisitParams) middleware.Responder {

                        list := params.IdList
                        log.Printf("%v\n",list)
                        return operations.NewTrackingRevisitOK().WithPayload("RESULT")
        })

I use

swagger generate server -A greeter -t gen -f ./swagger/swagger.yml

to generate the server from this yaml:

---
swagger: '2.0'
info:
  version: 1.0.0
  title: Greeting Server

basePath: "/api/greeting/2.0"

paths:
  /revisit:
    post:
      produces:
      - application/json
      consumes:
      - application/json
      parameters:
        - name: site
          required: true
          type: string
          in: query
          description: site name

        - name: userlist
          in: body
          description: list of users
          required: true
          schema:
            "$ref": "#/definitions/Userlist"

      operationId: trackingRevisit

      responses:
        200:
          description:  return list of users which need revisit
          schema:
            type: string


来源: stackexchange

问:
after save not direct to original page
This code is for save the data after key in form meeting. But when it's save it doesn't bring back to the original page.
It just showing blank page.  </p>

```<code>$datetime=date("Y-m-d H:i",strtotime($_POST['datetime']));
$type=$_POST['meeting_type'];
$bilno=$_POST['bilno'];
$total_agenda=$_POST['total_agenda'];
    $tablename="meeting_info";
    $sql_ins="INSERT INTO meeting_info(datetime, type, bilno, total_agenda) VALUES ( '$datetime','$type','$bilno', '$total_agenda')";
    $conn->query($sql_ins);

    $sql_id = "SELECT id FROM meeting_info ORDER BY id DESC LIMIT 1";
    $result = $conn->query($sql_id);

    if ($result->num_rows > 0)
    {
        // output data of each row
        if($row = $result->fetch_assoc())
        {
            $id=$row["id"];
            echo "<script type='text/javascript'>window.location.href='administration.php?id='.$id;</script>";
        }
    }
$conn->close();
</code>```

答:
you can try to redirect using </p>

```<code>header("location:administration.php?id=".$id);
</code>```

ContentLicense: CC BY-SA 3.0

Title: after save not direct to original page

Body:
This code is for save the data after key in form meeting. But when it's save it doesn't bring back to the original page.
It just showing blank page.

$datetime=date("Y-m-d H:i",strtotime($_POST['datetime']));
$type=$_POST['meeting_type'];
$bilno=$_POST['bilno'];
$total_agenda=$_POST['total_agenda'];
    $tablename="meeting_info";
    $sql_ins="INSERT INTO meeting_info(datetime, type, bilno, total_agenda) VALUES ( '$datetime','$type','$bilno', '$total_agenda')";
    $conn->query($sql_ins);

    $sql_id = "SELECT id FROM meeting_info ORDER BY id DESC LIMIT 1";
    $result = $conn->query($sql_id);

    if ($result->num_rows > 0)
    {
        // output data of each row
        if($row = $result->fetch_assoc())
        {
            $id=$row["id"];
            echo "";
        }
    }
$conn->close();

Body:
you can try to redirect using

header("location:administration.php?id=".$id);


答:
use this</p>

```<code> if ($conn->query($sql) === TRUE)
{
   header("refresh:1;url=index.php");
   exit;
}
</code>```

Title: after save not direct to original page

Body:
use this

 if ($conn->query($sql) === TRUE)
{
   header("refresh:1;url=index.php");
   exit;
}


问:
Custom Branding for Login on a Azure AD Multi-Tenant App
Question: How can I custom brand my Azure AD application login page? (note: NOT my org's login page; see below)

I have a web application hosted in Azure where users can log in using accounts that are created and managed within the application. Since my application is used by many big organizations, I have added the capability for customers to also sign in using their account that's managed by their organization (single sign on). This was done using Azure Active Directory, which syncs the local AD accounts into Azure where cloud authentication occurs. Since this application is used by many organizations all with their own separate ADs, I created the Active Directory application within Azure as multi-tenanted. With all of this done, the new login process works perfectly, however, I can't figure out how to brand the Microsoft hosted application sign in page.

Please keep in mind the distinction between the application login page and the organization's tenant login page. There is ample documentation about how to brand the organization's tenant login page, but not the application login page. Consider the application flow to understand the difference:

User goes to my app's login page, and chooses "Login with your existing organization account".

The user is redirected to a Microsoft hosted login page for my application. At this point, Microsoft/Azure Ad only knows which application this is for; it doesn't yet know who is logging in or which tenant (organization) they belong to. This is the login page I need help branding (logo & page background).

After the user enters their email address (and even before they enter their password), the user is redirected to a different login page--the login page for the user's organization (i.e. their tenant). This page shows that organization's custom branding if it was setup. This is not the login page I wish to brand; it is my customer's responsibility to brand their org if they desire.

After the user enters their password on their organization's login page, the user submits the form. Azure then successfully authenticates them and redirects them back to my application where they are now authenticated as well.

NOTE: this should be possible as you can see Microsoft is doing it on all of their cloud apps as well (Office 365, Visual Studio, Azure Portal)

NOTE: this question was asked over 3 years ago, but only 1 misdirected answer was given, and Azure and Azure AD has changed drastically since then. See: Azure Active Directory Custom Branded login page dont work with third party application. Also, the Microsoft documentation only covers the branding of the tenant login page, not the application login page like I am seeking. See: https://learn.microsoft.com/en-us/azure/active-directory/active-directory-add-company-branding.

答:
What you observe is only possible for Microsoft owned applications.
The customers can only brand their organisation login page.
What you can do however, is to redirect the user to your org login page. Then the first thing the user will see is your company branding. After they enter their login name, they may see their custom org login page (if the organisation has customized the login experience).
If you such a feature (per app custom login page) is something worth looking at, you can create a feature request on the UserVoice site - http://mygreatwindowsazureidea.com/

Just as a note - per app custom login page is today only possible on Azure AD B2C via custom policy implementation.


问:
Junit test hangs up on my async thread
I am fork a new thread on my service's @Postconstruct method, and in the new thread, a infinite loop is running.

My test is just invoke the service using spring mvc test:

```<code>ResultActions result = this.mockMvc.perform(post("/test").with(httpBasic(user, pwd)).contentType("application/json").content(test))
        .andDo(MockMvcResultHandlers.print())
        .andExpect(status().isOk());
</code>```

And the test just hangs there, waiting for the infinite loop thread to stop. but when the service is started normally, the test is fine. Any idea why? And how to fix it.

here is the code in my service java:

```<code>@Postconstruct
private void init() {
   invoke();
}

private void invoke() {

 Runnable task = () -> {
     while(true) { ... }
  }
 Thread t;
 for(int i=0; i<3; i++) {
     t = new Thread(task);
     t.setName("test-" + i);
     t.start();
  }
 }
</code>```

答:
Take a look at this example (with a debugger)

Notice that the main will not be exited until all the threads are done.
You can easily do this with putting a breakpoint on a while (run) and change the value of run slowly.    Once you turn off all 3 threads, then your main thread will exit.

```<code>class Test {
    public static void main(String[] args) {
        Runnable task = () -> {
            boolean run = true;
            while (run) {
                System.out.println("running");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Thread t = new Thread(task);
            t.setName("test-" + i);
            t.start();
            threads.add(t);
        }
    }
}
</code>```

Another way to do it is using join, which will explicitly wait for the threads to finish before the program can complete.

```<code>for (Thread t : threads) {
    try {
        t.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
</code>```

While there are any active threads running the program will not finish.

Title: Junit test hangs up on my async thread

Body:
I am fork a new thread on my service's @Postconstruct method, and in the new thread, a infinite loop is running.

My test is just invoke the service using spring mvc test:

ResultActions result = this.mockMvc.perform(post("/test").with(httpBasic(user, pwd)).contentType("application/json").content(test))
        .andDo(MockMvcResultHandlers.print())
        .andExpect(status().isOk());

And the test just hangs there, waiting for the infinite loop thread to stop. but when the service is started normally, the test is fine. Any idea why? And how to fix it.

here is the code in my service java:

@Postconstruct
private void init() {
   invoke();
}

private void invoke() {

 Runnable task = () -> {
     while(true) { ... }
  }
 Thread t;
 for(int i=0; i<3; i++) {
     t = new Thread(task);
     t.setName("test-" + i);
     t.start();
  }
 }

Body:
Take a look at this example (with a debugger)

Notice that the main will not be exited until all the threads are done.
You can easily do this with putting a breakpoint on a while (run) and change the value of run slowly.    Once you turn off all 3 threads, then your main thread will exit.

class Test {
    public static void main(String[] args) {
        Runnable task = () -> {
            boolean run = true;
            while (run) {
                System.out.println("running");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Thread t = new Thread(task);
            t.setName("test-" + i);
            t.start();
            threads.add(t);
        }
    }
}

Another way to do it is using join, which will explicitly wait for the threads to finish before the program can complete.

for (Thread t : threads) {
    try {
        t.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

While there are any active threads running the program will not finish.


问:
Is there a way to get the C++ virtual member function address
I searched this article:
C++ : Getting function virtual 'address' with member function pointer

In order to test if the virtual member function is usually at the beginning address of the object, I wrote the code as following:

```<code>#include <pwd.h>
#include <string.h>
#include <stdio.h>

class Base
{
public:
    int mBase1;
    char mBase2;
    virtual void foo()
    {
        fprintf(stderr,"Base foo called\n");
    }
};

class Child: public Base
{
public:
    int cc;
    virtual void foo()
    {
        fprintf(stderr,"Child foo called");
    }
};

int main(int argc, char *argv[])
{
    Base bb;
    fprintf(stderr,"[mBase1 %p][mBase2 %p] [foo %p]\n",&bb.mBase1,&bb.mBase2,&Base::foo);
    return 0;
}
</code>```

when compiling, I got a warning:

```<code>test.cpp:30:88: warning ‘%p’ expects argument of type ‘void*’, but argument 5 has type ‘void (Base::*)()’ [-Wformat]
</code>```

The output is:

```<code>[mBase1 0xbfc2ca38][mBase2 0xbfc2ca3c] [foo 0x1]
</code>```

I consider it's wired.

Is there any "pretty method" to get the member function (not static member function address?). Besides the following method, is there any other elegant way?

```<code>typedef void (Base::*Foo)();
Foo f = &Base::foo();
</code>```

Why doesn't &Base::foo get the correct C++ member address?

答:
As said before pointers to members are not pointers and their conversions to types like int or void * are meaningless in general. In particular the 0x1 most likely means the first or second entry in the vtable of the object.
Let's consider this code:

```<code>void (*Base::*test)() = &Base::foo
Child f;
f.*test();
</code>```

For the third line the compiler gets the address of f. Converts it to the address of a Base object, which in this case is a NOOP) reads from that address the address of the vtable for f (the vtable is usually the first data item in an object), then adds two that address 1*sizeof(void*) and calls the function at that address largely something equivalent to this C :

```<code>typedef void (*FnPtr)();
FnPtr *vtable=*(FnPtr **)&(Base &)f;
(*(vtable[(int)test]))(); or (*(vtable[(int)test - 1]))();
</code>```

This is only hypothesis which is likely true for the exact version of the compiler you have. No guarantee of portability even to future compiler versions.

Body:
I searched this article:
C++ : Getting function virtual 'address' with member function pointer

In order to test if the virtual member function is usually at the beginning address of the object, I wrote the code as following:

#include <pwd.h>
#include <string.h>
#include <stdio.h>

class Base
{
public:
    int mBase1;
    char mBase2;
    virtual void foo()
    {
        fprintf(stderr,"Base foo called\n");
    }
};

class Child: public Base
{
public:
    int cc;
    virtual void foo()
    {
        fprintf(stderr,"Child foo called");
    }
};

int main(int argc, char *argv[])
{
    Base bb;
    fprintf(stderr,"[mBase1 %p][mBase2 %p] [foo %p]\n",&bb.mBase1,&bb.mBase2,&Base::foo);
    return 0;
}

when compiling, I got a warning:

test.cpp:30:88: warning ‘%p’ expects argument of type ‘void*’, but argument 5 has type ‘void (Base::*)()’ [-Wformat]

The output is:

[mBase1 0xbfc2ca38][mBase2 0xbfc2ca3c] [foo 0x1]

I consider it's wired.

Is there any "pretty method" to get the member function (not static member function address?). Besides the following method, is there any other elegant way?

typedef void (Base::*Foo)();
Foo f = &Base::foo();

Why doesn't &Base::foo get the correct C++ member address?

Body:
As said before pointers to members are not pointers and their conversions to types like int or void * are meaningless in general. In particular the 0x1 most likely means the first or second entry in the vtable of the object.
Let's consider this code:

void (*Base::*test)() = &Base::foo
Child f;
f.*test();

For the third line the compiler gets the address of f. Converts it to the address of a Base object, which in this case is a NOOP) reads from that address the address of the vtable for f (the vtable is usually the first data item in an object), then adds two that address 1*sizeof(void*) and calls the function at that address largely something equivalent to this C :

typedef void (*FnPtr)();
FnPtr *vtable=*(FnPtr **)&(Base &)f;
(*(vtable[(int)test]))(); or (*(vtable[(int)test - 1]))();

This is only hypothesis which is likely true for the exact version of the compiler you have. No guarantee of portability even to future compiler versions.


问:
What's the replacement for Xcode's PackageApplication?
With Xcode 8.3 PackageApplication is gone. I did use it to convert an *.app package/directory to a *.ipa file (after re-signing):

```<code>xcrun -sdk iphoneos PackageApplication -v "MyApp.app" -o "MyApp.ipa"
</code>```

Is there any replacement for this, so I can continue to convert .app to .ipa?

答:
This is the error:
xcrun: error: unable to find utility "PackageApplication", not a developer tool or in PATH
It looks like PackageApplication is removed from Xcode 8.3.
In Xcode 8.2 there was a warning: PackageApplication is deprecated, use xcodebuild -exportArchive instead.

Body:
With Xcode 8.3 PackageApplication is gone. I did use it to convert an *.app package/directory to a *.ipa file (after re-signing):

xcrun -sdk iphoneos PackageApplication -v "MyApp.app" -o "MyApp.ipa"

Is there any replacement for this, so I can continue to convert .app to .ipa?


问:
Unexpected error when deserializing unknown types with Json.Net
In the following code, I serialize an object using Json.Net. This Json has type names embedded. I then change one of the type names to induce an error (this is a test, I am dealing with a real issue in an existing project). When I deserialize the Json, I expect to get an object back that has a null value for the property with the fiddled type name. Instead the serializer craps out and returns null. Are my expectations correct? Can I change the settings somehow so that I will get a non-null object for my root object? Note that the second error that I get suggests that there is a bug in the serializer.</p>

```<code>static public class JsonTest
{
    static public void Test()
    {
        // Create test object
        A a = new A
        {
            MyTest = new MyTest(),
        };

        // Serialize it.
        string json = JsonConvert.SerializeObject(a, new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Auto
        });

        // Fiddle class name to induce error
        json = json.Replace("+MyTest", "+MyTest2");

        // Before: {"MyTest":{"$type":"<Namespace>.JsonTest+MyTest, <Assembly>"}}
        // After: {"MyTest":{"$type":"<Namespace>.JsonTest+MyTest2, <Assembly>"}}

        // Deserialize
        A a2 = JsonConvert.DeserializeObject<A>(json, new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Auto,
            Error = (object sender, ErrorEventArgs e) =>
            {
                e.ErrorContext.Handled = true; // Should have only one error: the unrecognized Type
            }
        });

        // A second error occurs: Error = {Newtonsoft.Json.JsonSerializationException: Additional text found in JSON string after finishing deserializing object....
        // a2 is null
    }

    public class A
    {
        public ITest MyTest { get; set; }
    }

    public interface ITest { }
    public class MyTest : ITest { }
}
</code>```

答:
Update

This issue has been fixed in Json.NET 10.0.2 in this submission.

Original Answer

This looks to be a bug in Json.NET.  If I set JsonSerializerSettings.MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead then the problem goes away:

```<code>// Deserialize
A a2 = JsonConvert.DeserializeObject<A>(json, new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.Auto,
    MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead,
    Error = (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs e) =>
    {
        Debug.WriteLine(e.ErrorContext.Path);
        e.ErrorContext.Handled = true; // Should have only one error: the unrecognized Type
    }
});

Debug.Assert(a2 != null); // No assert.
</code>```

However, it should not be necessary to turn on this setting, which enables reading metadata properties including "$type" located anywhere in a JSON object, rather than just as the first property.  Most likely it coincidentally fixes the bug since it requires pre-loading the entire JSON object before beginning deserialization.

You could report an issue if you want.

Debugging a bit, the problem seems to be that, because the inner MyTest object cannot be constructed, the exception is caught and handled by JsonSerializerInternalReader.PopulateObject() while populating the outer object A.  Because of this, the JsonReader does not get advanced past the inner, nested object, leaving the reader and serializer in an inconsistent state.  This accounts for the second exception and the eventual Additional text found in JSON string after finishing deserializing object. Path '' exception.

Body:
In the following code, I serialize an object using Json.Net. This Json has type names embedded. I then change one of the type names to induce an error (this is a test, I am dealing with a real issue in an existing project). When I deserialize the Json, I expect to get an object back that has a null value for the property with the fiddled type name. Instead the serializer craps out and returns null. Are my expectations correct? Can I change the settings somehow so that I will get a non-null object for my root object? Note that the second error that I get suggests that there is a bug in the serializer.

static public class JsonTest
{
    static public void Test()
    {
        // Create test object
        A a = new A
        {
            MyTest = new MyTest(),
        };

        // Serialize it.
        string json = JsonConvert.SerializeObject(a, new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Auto
        });

        // Fiddle class name to induce error
        json = json.Replace("+MyTest", "+MyTest2");

        // Before: {"MyTest":{"$type":"<Namespace>.JsonTest+MyTest, <Assembly>"}}
        // After: {"MyTest":{"$type":"<Namespace>.JsonTest+MyTest2, <Assembly>"}}

        // Deserialize
        A a2 = JsonConvert.DeserializeObject(json, new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Auto,
            Error = (object sender, ErrorEventArgs e) =>
            {
                e.ErrorContext.Handled = true; // Should have only one error: the unrecognized Type
            }
        });

        // A second error occurs: Error = {Newtonsoft.Json.JsonSerializationException: Additional text found in JSON string after finishing deserializing object....
        // a2 is null
    }

    public class A
    {
        public ITest MyTest { get; set; }
    }

    public interface ITest { }
    public class MyTest : ITest { }
}

Body:
Update

This issue has been fixed in Json.NET 10.0.2 in this submission.

Original Answer

This looks to be a bug in Json.NET.  If I set JsonSerializerSettings.MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead then the problem goes away:

// Deserialize
A a2 = JsonConvert.DeserializeObject<A>(json, new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.Auto,
    MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead,
    Error = (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs e) =>
    {
        Debug.WriteLine(e.ErrorContext.Path);
        e.ErrorContext.Handled = true; // Should have only one error: the unrecognized Type
    }
});

Debug.Assert(a2 != null); // No assert.

However, it should not be necessary to turn on this setting, which enables reading metadata properties including "$type" located anywhere in a JSON object, rather than just as the first property.  Most likely it coincidentally fixes the bug since it requires pre-loading the entire JSON object before beginning deserialization.

You could report an issue if you want.

Debugging a bit, the problem seems to be that, because the inner MyTest object cannot be constructed, the exception is caught and handled by JsonSerializerInternalReader.PopulateObject() while populating the outer object A.  Because of this, the JsonReader does not get advanced past the inner, nested object, leaving the reader and serializer in an inconsistent state.  This accounts for the second exception and the eventual Additional text found in JSON string after finishing deserializing object. Path '' exception.


问:
Has installation been successful or there is any error?
This is the command prompt where I am installing the tensor flow in Anaconda:

I am new to Python and I want to use Tensorflow. But on installing TensorFlow inside Anaconda, I am shown this on validating the installation process.

答:
This is a known issue with TensorFlow 1.0 on Windows. The error messages are harmless, you did nothing wrong, and you can ignore them.

The issue has been fixed in TensorFlow 1.1, for which a release candidate was just published. You can upgrade to it by running the following command at the command prompt:

```<code>C:\> pip install --upgrade tensorflow==1.1.0rc0
</code>```

Body:
This is a known issue with TensorFlow 1.0 on Windows. The error messages are harmless, you did nothing wrong, and you can ignore them.

The issue has been fixed in TensorFlow 1.1, for which a release candidate was just published. You can upgrade to it by running the following command at the command prompt:

C:\> pip install --upgrade tensorflow==1.1.0rc0


问:
Database with Multi Master replication
What are good options for a multi master replication enabled, scalable database. We are talking about 15-16 TB of data. We are thinking DynamoDB. Are there any more databases which we should look up.
Any advice on DynamoDB usage as well as new ideas about the required database type is welcome.</p>

答: Currently, DynamoDB supports cross-region replication with the cross-region replication library on Github. It should be somewhat straightforward to divide up the partition and sort key space by region and then run the library in each region. You would have to modify the library to ignore stream records for items that are not mastered in the region (each region should only propagate changes for items mastered in that region). In this setup, each master-replica table in each region will have a stream enabled and each region should have an EC2 instance processing that table's DynamoDB stream.</p>

Title: Database with Multi Master replication


问:
Swift 3.0 - Drawing on imageView with finger
I have been working on being able to draw a red line on an image view using swift 3.0 and have ran across some problems. As you could guess, I am using some code from stack overflow to help me with my first initial attempt at this and am getting a weird bug.

As I drag my finger across the imageview it does draw a red line but for each "frame" it drops all that I drew down further on the screen. So as I draw it looks like the lines I am drawing are falling and then just completely go off screen.

What I am looking for is to be able to simply draw on the image view and instead of everything moving down each frame, I would like it to keep in the same position similar to how it works on all the drawing apps and etc.

Below is all the code:

```<code>@IBOutlet weak var mainImageView: UIImageView!
var lastPoint = CGPoint.zero
var fromPoint = CGPoint();
var toPoint = CGPoint.zero
var red: CGFloat = 255.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var brushWidth: CGFloat = 10.0
var opacity: CGFloat = 1.0
var swiped = false

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint)
{
    UIGraphicsBeginImageContextWithOptions(self.mainImageView.bounds.size, false, 0);
    mainImageView.image?.draw(in: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))
    let context = UIGraphicsGetCurrentContext()

    context?.move(to: fromPoint)
    context?.addLine(to: toPoint)
    context?.setLineCap(CGLineCap.round)
    context?.setLineWidth(brushWidth)
    context?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
    context?.setBlendMode(CGBlendMode.normal)
    context?.strokePath()

    mainImageView.image = UIGraphicsGetImageFromCurrentImageContext()
    mainImageView.alpha = opacity
    UIGraphicsEndImageContext()

}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = false;
    if let touch = touches.first {
        lastPoint = touch.location(in: self.mainImageView)
    }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = true;
    if let touch = touches.first {
        let currentPoint = touch.location(in: mainImageView)
        drawLineFrom(fromPoint: lastPoint, toPoint: currentPoint)
        lastPoint = currentPoint
    }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if(!swiped){
        self.drawLineFrom(fromPoint: lastPoint, toPoint: lastPoint)
    }
}
</code>```

Thanks for the help guys!

答:
Following code you can Draw the image using touch</p>

```<code>override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

if let touch = touches.first as? UITouch{

    prevPoint1 = touch.previousLocationInView(self.view)

    prevPoint2 = touch.previousLocationInView(self.view)

    lastPoint = touch.locationInView(self.view)

}

}

 override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {

if let touch = touches.first as? UITouch{

    let currentPoint = touch.locationInView(view)

    prevPoint2 = prevPoint1

    prevPoint1 = touch.previousLocationInView(self.view)

    UIGraphicsBeginImageContext(view.frame.size)

    let context = UIGraphicsGetCurrentContext()

    TempImage.image?.drawInRect(CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))

    var mid1 = CGPointMake((prevPoint1.x + prevPoint2.x)*0.5, (prevPoint1.y + prevPoint2.y)*0.5)

    var mid2 = CGPointMake((currentPoint.x + prevPoint1.x)*0.5, (currentPoint.y + prevPoint1.y)*0.5)

    CGContextMoveToPoint(context, mid1.x, mid1.y)

    CGContextAddQuadCurveToPoint(context, prevPoint1.x, prevPoint1.y, mid2.x, mid2.y)

    //CGContextAddLineToPoint(context, toPoint.x, toPoint.y)

    CGContextSetLineCap(context, kCGLineCapRound)

    CGContextSetLineWidth(context, brushWidth)

    CGContextSetRGBStrokeColor(context, red, green,blue, 1.0)

    CGContextSetBlendMode(context, kCGBlendModeNormal)

    CGContextStrokePath(context)

    TempImage.image = UIGraphicsGetImageFromCurrentImageContext()

    TempImage.alpha = opacity

    UIGraphicsEndImageContext()

    lastPoint = currentPoint

}

 }

 override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {

UIGraphicsBeginImageContext(MainImage.frame.size)

MainImage.image?.drawInRect(CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height), blendMode: kCGBlendModeNormal, alpha: 1.0)

TempImage.image?.drawInRect(CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height), blendMode: kCGBlendModeNormal, alpha: opacity)

MainImage.image = UIGraphicsGetImageFromCurrentImageContext()

UIGraphicsEndImageContext()

TempImage.image = nil

}
</code>```

Body:
I have been working on being able to draw a red line on an image view using swift 3.0 and have ran across some problems. As you could guess, I am using some code from stack overflow to help me with my first initial attempt at this and am getting a weird bug.

As I drag my finger across the imageview it does draw a red line but for each "frame" it drops all that I drew down further on the screen. So as I draw it looks like the lines I am drawing are falling and then just completely go off screen.

What I am looking for is to be able to simply draw on the image view and instead of everything moving down each frame, I would like it to keep in the same position similar to how it works on all the drawing apps and etc.

Below is all the code:

@IBOutlet weak var mainImageView: UIImageView!
var lastPoint = CGPoint.zero
var fromPoint = CGPoint();
var toPoint = CGPoint.zero
var red: CGFloat = 255.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var brushWidth: CGFloat = 10.0
var opacity: CGFloat = 1.0
var swiped = false

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint)
{
    UIGraphicsBeginImageContextWithOptions(self.mainImageView.bounds.size, false, 0);
    mainImageView.image?.draw(in: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))
    let context = UIGraphicsGetCurrentContext()

    context?.move(to: fromPoint)
    context?.addLine(to: toPoint)
    context?.setLineCap(CGLineCap.round)
    context?.setLineWidth(brushWidth)
    context?.setStrokeColor(red: red, green: green, blue: blue, alpha: 1.0)
    context?.setBlendMode(CGBlendMode.normal)
    context?.strokePath()

    mainImageView.image = UIGraphicsGetImageFromCurrentImageContext()
    mainImageView.alpha = opacity
    UIGraphicsEndImageContext()

}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = false;
    if let touch = touches.first {
        lastPoint = touch.location(in: self.mainImageView)
    }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = true;
    if let touch = touches.first {
        let currentPoint = touch.location(in: mainImageView)
        drawLineFrom(fromPoint: lastPoint, toPoint: currentPoint)
        lastPoint = currentPoint
    }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if(!swiped){
        self.drawLineFrom(fromPoint: lastPoint, toPoint: lastPoint)
    }
}

Thanks for the help guys!

Body:
Following code you can Draw the image using touch

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

if let touch = touches.first as? UITouch{

    prevPoint1 = touch.previousLocationInView(self.view)

    prevPoint2 = touch.previousLocationInView(self.view)

    lastPoint = touch.locationInView(self.view)

}

}

 override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {

if let touch = touches.first as? UITouch{

    let currentPoint = touch.locationInView(view)

    prevPoint2 = prevPoint1

    prevPoint1 = touch.previousLocationInView(self.view)

    UIGraphicsBeginImageContext(view.frame.size)

    let context = UIGraphicsGetCurrentContext()

    TempImage.image?.drawInRect(CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))

    var mid1 = CGPointMake((prevPoint1.x + prevPoint2.x)*0.5, (prevPoint1.y + prevPoint2.y)*0.5)

    var mid2 = CGPointMake((currentPoint.x + prevPoint1.x)*0.5, (currentPoint.y + prevPoint1.y)*0.5)

    CGContextMoveToPoint(context, mid1.x, mid1.y)

    CGContextAddQuadCurveToPoint(context, prevPoint1.x, prevPoint1.y, mid2.x, mid2.y)

    //CGContextAddLineToPoint(context, toPoint.x, toPoint.y)

    CGContextSetLineCap(context, kCGLineCapRound)

    CGContextSetLineWidth(context, brushWidth)

    CGContextSetRGBStrokeColor(context, red, green,blue, 1.0)

    CGContextSetBlendMode(context, kCGBlendModeNormal)

    CGContextStrokePath(context)

    TempImage.image = UIGraphicsGetImageFromCurrentImageContext()

    TempImage.alpha = opacity

    UIGraphicsEndImageContext()

    lastPoint = currentPoint

}

 }

 override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {

UIGraphicsBeginImageContext(MainImage.frame.size)

MainImage.image?.drawInRect(CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height), blendMode: kCGBlendModeNormal, alpha: 1.0)

TempImage.image?.drawInRect(CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height), blendMode: kCGBlendModeNormal, alpha: opacity)

MainImage.image = UIGraphicsGetImageFromCurrentImageContext()

UIGraphicsEndImageContext()

TempImage.image = nil

}


问:
PHP - How to get the value of json api using Php?
I have a question regarding on json.. I tried to get an api from other site and downloaded it as json file..I've already decoded this file using this code below..

```<code>$str = file_get_contents('../trelloApi.json');
$json = json_decode($str, true);
echo '```' . print_r($json, true) . '```';
</code>```

From this image attached, how do I get or print the value of the [list] => Array, [board] => Array and [card] => Array?

Please help me :(

答:
After json_decode you can this way retrieve 'list','board' and 'card' array data....May be help you.. </p>

```<code>$list=array();
$board=array();
$card=array();

foreach($json as $key => $value){

   $list[]=$value[$key]['data']['list'];
   $board[]=$value[$key]['data']['board'];
   $card[]=$value[$key]['data']['card'];
}

echo "```";
print_r($list);
print_r($board);
print_r($card);
</code>```

Body:
I have a question regarding on json.. I tried to get an api from other site and downloaded it as json file..I've already decoded this file using this code below..

$str = file_get_contents('../trelloApi.json');
$json = json_decode($str, true);
echo '
' . print_r($json, true) . '
';

From this image attached, how do I get or print the value of the [list] => Array, [board] => Array and [card] => Array?

Please help me :(

Body:
After json_decode you can this way retrieve 'list','board' and 'card' array data....May be help you..

$list=array();
$board=array();
$card=array();

foreach($json as $key => $value){

   $list[]=$value[$key]['data']['list'];
   $board[]=$value[$key]['data']['board'];
   $card[]=$value[$key]['data']['card'];
}

echo "<pre>";
print_r($list);
print_r($board);
print_r($card);


问:
multiple numpy dot products without a loop
Is it possible to compute several dot products without a loop?
say you have the following:

```<code>a = randn(100, 3, 3)
b = randn(100, 3, 3)
</code>```

I want to get an array z of shape (100, 3, 3) such that for all i

```<code>z[i, ...] == dot(a[i, ...], b[i, ...])
</code>```

in other words, which verifies:

```<code>for va, vb, vz in izip(a, b, z):
    assert (vq == dot(va, vb)).all()
</code>```

The straightforward solution would be:

```<code>z = array([dot(va, vb) for va, vb in zip(a, b)])
</code>```

which uses an implicit loop (list comprehension + array).

Is there a more efficient way to compute z?

答:
In addition to the other answers, I want to add that:

```<code>np.einsum("ijk, ijk -> ij", a, b)
</code>```

Is suitable for a related case I encountered, where you have two 3D arrays consisting of matching 2D fields of 2D vectors (points or directions). This gives a kind of "element-wise" dot product between those 2D vectors.

For example:

```<code>np.einsum("ijk, ijk -> ij", [[[1,2],[3,4]]], [[[5,6],[7,8]]])
# => array([[17, 53]])
</code>```

Where:

```<code>np.dot([1,2],[5,6])
# => 17
np.dot([3,4],[7,8])
# => 53
</code>```

Body:
Is it possible to compute several dot products without a loop?
say you have the following:

a = randn(100, 3, 3)
b = randn(100, 3, 3)

I want to get an array z of shape (100, 3, 3) such that for all i

z[i, ...] == dot(a[i, ...], b[i, ...])

in other words, which verifies:

for va, vb, vz in izip(a, b, z):
    assert (vq == dot(va, vb)).all()

The straightforward solution would be:

z = array([dot(va, vb) for va, vb in zip(a, b)])

which uses an implicit loop (list comprehension + array).

Is there a more efficient way to compute z?

Body:
In addition to the other answers, I want to add that:

np.einsum("ijk, ijk -> ij", a, b)

Is suitable for a related case I encountered, where you have two 3D arrays consisting of matching 2D fields of 2D vectors (points or directions). This gives a kind of "element-wise" dot product between those 2D vectors.

For example:

np.einsum("ijk, ijk -> ij", [[[1,2],[3,4]]], [[[5,6],[7,8]]])
# => array([[17, 53]])

Where:

np.dot([1,2],[5,6])
# => 17
np.dot([3,4],[7,8])
# => 53


问:
Vim autocmd error
I have this script to set variables when loading Python files

```<code>au BufNewFile,BufRead *.py
    \ set tabstop=4
    \ set softtabstop=4
    \ set shiftwidth=4
    \ set textwidth=79
    \ set expandtab
    \ set autoindent
    \ set fileformat=unix
</code>```

When I load a Python file I get this error:

```<code>Error detected while processing BufRead Auto commands for "*.py":
E518: Unknown option: set
</code>```

答:
The following are a couple of ways of achieving what you want :

```<code>au BufNewFile,BufRead *.py
    \ set tabstop=4 |
    \ set softtabstop=4 |
    \ set shiftwidth=4 |
    \ set textwidth=79 |
    \ set expandtab |
    \ set autoindent |
    \ set fileformat=unix
</code>```

OR

```<code>au BufNewFile,BufRead *.py
    \ set tabstop=4
    \ softtabstop=4
    \ shiftwidth=4
    \ textwidth=79
    \ expandtab
    \ autoindent
    \ fileformat=unix
</code>```

Explanation :

In your autocommand you're calling the :set (:h :set) command which
  is used to set vim options. If you want to set multiple options, you
  can either call :set with multiple options separated with whitespace
  or call :set multiple times for each option, separating each :set
  command with the | (:h :bar).

Tip :

Since your objective is to define certain options specifically for
  python files, you should either use :autocmd Filetype python ... for
  this, or better yet create a ftplugin/python/custom.vim file where
  you can enable these settings using the :setlocal command as opposed
  to :set to set them only for the current buffer.

Title: Vim autocmd error

Body:
I have this script to set variables when loading Python files

au BufNewFile,BufRead *.py
    \ set tabstop=4
    \ set softtabstop=4
    \ set shiftwidth=4
    \ set textwidth=79
    \ set expandtab
    \ set autoindent
    \ set fileformat=unix

When I load a Python file I get this error:

Error detected while processing BufRead Auto commands for "*.py":
E518: Unknown option: set

Body:
The following are a couple of ways of achieving what you want :

au BufNewFile,BufRead *.py
    \ set tabstop=4 |
    \ set softtabstop=4 |
    \ set shiftwidth=4 |
    \ set textwidth=79 |
    \ set expandtab |
    \ set autoindent |
    \ set fileformat=unix

OR

au BufNewFile,BufRead *.py
    \ set tabstop=4
    \ softtabstop=4
    \ shiftwidth=4
    \ textwidth=79
    \ expandtab
    \ autoindent
    \ fileformat=unix

Explanation :

In your autocommand you're calling the :set (:h :set) command which
  is used to set vim options. If you want to set multiple options, you
  can either call :set with multiple options separated with whitespace
  or call :set multiple times for each option, separating each :set
  command with the | (:h :bar).

Tip :

Since your objective is to define certain options specifically for
  python files, you should either use :autocmd Filetype python ... for
  this, or better yet create a ftplugin/python/custom.vim file where
  you can enable these settings using the :setlocal command as opposed
  to :set to set them only for the current buffer.


问:
MobileServiceAuthenticationProvider.MicrosoftAccount,token<-????) from where can I get token
I'm trying to implement Microsoft authentication for a mobile app that connect to a Azure mobile back end service, I created a  MobileServiceUser user; then I tried to use the method LoginAsync and already choosed the Micorosft Provider, the question is from where can I get the token value

user = await App.Client.LoginAsync( MobileServiceAuthenticationProvider.MicrosoftAccount,token<-????);

I try to get info about that

Thank you

答:
Not sure if you ever got an answer to this question but you get the token from a client managed authentication.  You independently use each of the provider API (Facebook, Google, Microsoft, LinkedIn, etc.) and then when you authenticate it using OAuth, you will get a token back.  Then you pass the token into the LoginAsync call.

Here's some sample code:

```<code>                    auth = new OAuth2Authenticator(
             clientId: "MyAppId",  // For Facebook login, for configure refer http://www.c-sharpcorner.com/article/register-identity-provider-for-new-oauth-application/
             scope: "",
             authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"), // These values do not need changing
             redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html")// These values do not need changing

// After facebook,google and all identity provider login completed
                    auth.Completed += Auth_Completed;

    private async void Auth_Completed(object sender, Xamarin.Auth.AuthenticatorCompletedEventArgs e)
    {
        if (e.IsAuthenticated)
        {

string token = e.Account.Properties["access_token"];
           }
    }
</code>```

You then pass this token in the LoginAsync method.

Body:
Not sure if you ever got an answer to this question but you get the token from a client managed authentication.  You independently use each of the provider API (Facebook, Google, Microsoft, LinkedIn, etc.) and then when you authenticate it using OAuth, you will get a token back.  Then you pass the token into the LoginAsync call.

Here's some sample code:

                    auth = new OAuth2Authenticator(
             clientId: "MyAppId",  // For Facebook login, for configure refer http://www.c-sharpcorner.com/article/register-identity-provider-for-new-oauth-application/
             scope: "",
             authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"), // These values do not need changing
             redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html")// These values do not need changing

// After facebook,google and all identity provider login completed
                    auth.Completed += Auth_Completed;

    private async void Auth_Completed(object sender, Xamarin.Auth.AuthenticatorCompletedEventArgs e)
    {
        if (e.IsAuthenticated)
        {

string token = e.Account.Properties["access_token"];
           }
    }

You then pass this token in the LoginAsync method.


问:
IE 11 flexbox child width not respecting content (Safari too)
I have a strange bug that I seem to keep stumbling upon and I'd like to know what is actually going on here. I have a flexbox container (row wrap) with two child divs (flex: 1). When I have a heading that I don't want to wrap (white-space: nowrap), IE 11's containing div doesn't respect its width and shrinks to less than the header width. This seems to work just fine in Chrome, but Safari and IE seem to not respect the heading's width. What's going on here?

Here is the js bin: https://jsbin.com/bowodiz/edit?css,output

I have put the main styles and markup inline below for convenience sake.

HTML:

```<code><div class="flex-container">

    <div class="left">
      <div class="heading">Here is a heading that shouldn't wrap</div>
      <div class="sub-text">This is just some content that should wrap just fine ..</div>
    </div>

    <div class="right">
      <div class="heading">Here is a heading that shouldn't wrap</div>
      <div class="sub-text">This is just some content that should wrap just fine ...</div>
    </div>

</div>
</code>```

CSS (partial):

```<code>.flex-container {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}

.flex-container > div {
  flex: 1;
}

.heading {
  white-space: nowrap;
}
</code>```

Desired:

IE/Safari Behavior:

答:
Instead of flex: 1 use flex-grow: 1; flex-basis: 0; or specify all 3 values that you want for the shorthand. And if you specify flex-basis make sure you specify a unit. https://jsbin.com/ketolifuhu/edit?html,css,output

Here's a good article that covers some of the bugs and inconsistencies https://philipwalton.com/articles/normalizing-cross-browser-flexbox-bugs/

:root {
    --dark-primary-color: #303F9F;
    --default-primary-color: #3F51B5;
    --light-primary-color: #C5CAE9;
    --text-primary-color: #FFFFFF;
    --accent-color: #FF4081;
    --primary-text-color: #212121;
    --secondary-text-color: #757575;
    --divider-color: #BDBDBD;
    --box-size: 150px;
    font-family: Roboto, 'sans-serif';
    font-size: 20px;
    letter-spacing: 1.25px;
    font-weight: 100;
    color: white;
}

body {
  background-color: #BDBDBD;
}

.flex-container {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}

.flex-container > div {
  flex-grow: 1;
  margin: 10px;
  box-shadow: 2px 2px 6px 1px rgba(0,0,0,.2);
  padding: 30px;
  flex-basis: 0;
}

.left {
  background-color: #3F51B5;
}

.right {
  background-color: #3F51B5;
}

.heading {
  letter-spacing: .5px;
  font-weight: 400;
  white-space: nowrap;
}

.sub-text {
  margin-top: 20px;
  font-size: 14px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <link href="https://fonts.googleapis.com/css?family=Roboto:100,400" rel="stylesheet">
  <title>JS Bin</title>
</head>
<body>

  <div class="flex-container">

    <div class="left">
      <div class="heading">Here is a heading that shouldn't wrap</div>
      <div class="sub-text">This is just some content that should wrap just fine and I don't really care what it says, but it'll just wrap just fine and that behavior should be handled by the heading.</div>
    </div>
    <div class="right">
      <div class="heading">Here is a heading that shouldn't wrap</div>
      <div class="sub-text">This is just some content that should wrap just fine and I don't really care what it says, but it'll just wrap just fine and that behavior should be handled by the heading.</div>
    </div>

  </div>

</body>
</html></code>```

Body:
I have a strange bug that I seem to keep stumbling upon and I'd like to know what is actually going on here. I have a flexbox container (row wrap) with two child divs (flex: 1). When I have a heading that I don't want to wrap (white-space: nowrap), IE 11's containing div doesn't respect its width and shrinks to less than the header width. This seems to work just fine in Chrome, but Safari and IE seem to not respect the heading's width. What's going on here?

Here is the js bin: https://jsbin.com/bowodiz/edit?css,output

I have put the main styles and markup inline below for convenience sake.

HTML:

Here is a heading that shouldn't wrap

This is just some content that should wrap just fine ..

Here is a heading that shouldn't wrap

This is just some content that should wrap just fine ...

CSS (partial):

.flex-container {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}

.flex-container > div {
  flex: 1;
}

.heading {
  white-space: nowrap;
}

Desired:

IE/Safari Behavior:

Body:
Instead of flex: 1 use flex-grow: 1; flex-basis: 0; or specify all 3 values that you want for the shorthand. And if you specify flex-basis make sure you specify a unit. https://jsbin.com/ketolifuhu/edit?html,css,output

Here's a good article that covers some of the bugs and inconsistencies https://philipwalton.com/articles/normalizing-cross-browser-flexbox-bugs/

:root {
    --dark-primary-color: #303F9F;
    --default-primary-color: #3F51B5;
    --light-primary-color: #C5CAE9;
    --text-primary-color: #FFFFFF;
    --accent-color: #FF4081;
    --primary-text-color: #212121;
    --secondary-text-color: #757575;
    --divider-color: #BDBDBD;
    --box-size: 150px;
    font-family: Roboto, 'sans-serif';
    font-size: 20px;
    letter-spacing: 1.25px;
    font-weight: 100;
    color: white;
}

body {
  background-color: #BDBDBD;
}

.flex-container {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}

.flex-container > div {
  flex-grow: 1;
  margin: 10px;
  box-shadow: 2px 2px 6px 1px rgba(0,0,0,.2);
  padding: 30px;
  flex-basis: 0;
}

.left {
  background-color: #3F51B5;
}

.right {
  background-color: #3F51B5;
}

.heading {
  letter-spacing: .5px;
  font-weight: 400;
  white-space: nowrap;
}

.sub-text {
  margin-top: 20px;
  font-size: 14px;
}

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <link href="https://fonts.googleapis.com/css?family=Roboto:100,400" rel="stylesheet">
  <title>JS Bin</title>
</head>
<body>

  <div class="flex-container">

    <div class="left">
      <div class="heading">Here is a heading that shouldn't wrap</div>
      <div class="sub-text">This is just some content that should wrap just fine and I don't really care what it says, but it'll just wrap just fine and that behavior should be handled by the heading.</div>
    </div>
    <div class="right">
      <div class="heading">Here is a heading that shouldn't wrap</div>
      <div class="sub-text">This is just some content that should wrap just fine and I don't really care what it says, but it'll just wrap just fine and that behavior should be handled by the heading.</div>
    </div>

  </div>

</body>
</html>


问:
how to access history object in new React Router v4
I have tried all the suggested ways in other threads and it is still not working which is why I am posting the question.

So I have history.js looking like this

```<code>import { createBrowserHistory } from 'history';

export default createBrowserHistory;
</code>```

My index.js

```<code>render((
        <Router history={history}>
            <div>
                <Route component={App}/>
            </div>
        </Router>
    ), document.getElementById('root')
);
</code>```

Home.js Looks like this

```<code>class Home extends Component {
    handleSubmit(e) {
        e.preventDefault();

        let teacherName = e.target.elements[0].value;
        let teacherTopic = e.target.elements[1].value;
        let path = `/featured/${teacherName}/${teacherTopic}`;
        history.push(path);

    }

    render() {
        return (
            <div className="main-content home">
                <hr />
                <h3>Featured Teachers</h3>
                <form onSubmit={this.handleSubmit}>
                    <input type="text" placeholder="Name"/>
                    <input type="text" placeholder="Topic"/>
                    <button type="submit"> Submit </button>
                </form>
            </div>
        );
    }
}

export default Home;
</code>```

Home.js is actually routed in app.js which is routed in index.js.

The problem is that I cannot access history object anywhere.

The ways I have tried are as below

1) this.context.history.push(path) in home.js - cannot access context of undefined

2) this.props.history.push(path) in home.js - cannot access props of undefined

3) browserHistory.push(path) in index.js - this is deprecated now

4) the way above - _history2.default.push is not a function

None of the methods that I have tried above works. The second was the strangest as I should be able to access history object as props anywhere according to the documentation https://reacttraining.com/react-router/web/api/Route/Route-render-methods

I know the previous v2 or v3 way of accessing history is also deprecated.

So can someone who knows how to access history object in React Router v4 answer this question? Thanks.

答:
Looks to me like you might be missing a withRouter connection. this would make the history props available to this component

```<code>...

import { withRouter } from 'react-router'

class Home extends Component {
  functionMethod() {
    const { history: { push } } = this.props;
    doStuff();
    push('/location');
  }
  ...
}

export default withRouter(Home);
</code>```

https://reacttraining.com/react-router/web/api/withRouter

Body:
I have tried all the suggested ways in other threads and it is still not working which is why I am posting the question.

So I have history.js looking like this

import { createBrowserHistory } from 'history';

export default createBrowserHistory;

My index.js

render((
        <Router history={history}>

                <Route component={App}/>

        </Router>
    ), document.getElementById('root')
);

Home.js Looks like this

class Home extends Component {
    handleSubmit(e) {
        e.preventDefault();

        let teacherName = e.target.elements[0].value;
        let teacherTopic = e.target.elements[1].value;
        let path = `/featured/${teacherName}/${teacherTopic}`;
        history.push(path);

    }

    render() {
        return (

Featured Teachers

                <form onSubmit={this.handleSubmit}>
                    <input type="text" placeholder="Name"/>
                    <input type="text" placeholder="Topic"/>
                    <button type="submit"> Submit </button>
                </form>

        );
    }
}

export default Home;

Home.js is actually routed in app.js which is routed in index.js.

The problem is that I cannot access history object anywhere.

The ways I have tried are as below

1) this.context.history.push(path) in home.js - cannot access context of undefined

2) this.props.history.push(path) in home.js - cannot access props of undefined

3) browserHistory.push(path) in index.js - this is deprecated now

4) the way above - _history2.default.push is not a function

None of the methods that I have tried above works. The second was the strangest as I should be able to access history object as props anywhere according to the documentation https://reacttraining.com/react-router/web/api/Route/Route-render-methods

I know the previous v2 or v3 way of accessing history is also deprecated.

So can someone who knows how to access history object in React Router v4 answer this question? Thanks.

Body:
Looks to me like you might be missing a withRouter connection. this would make the history props available to this component

...

import { withRouter } from 'react-router'

class Home extends Component {
  functionMethod() {
    const { history: { push } } = this.props;
    doStuff();
    push('/location');
  }
  ...
}

export default withRouter(Home);

https://reacttraining.com/react-router/web/api/withRouter


问:
How to convert a dict inside a list to a DataFrame in python?
Python beginner here. I am struggling to dump my list of dicts into a pandas.DataFrame the right away. My data has the following structure.

```<code>a = {'Scores': {'s1': [{'Math': '95',
'Science': '74.5',
'English': '60.5'},
{'Math': '87.9',
'Science': '97.3',
'English': '78.3'}],
's2': [{'Math': '67.2',
'Science': '74.2',
'English': '89'}]}}
</code>```

My pandas.Dataframe columns should be the subjects 'Math', 'Science' and 'English' and the rows should be the scores. The columns are dynamically created so I can not explicitly mention the column names to call it. All I need are the values of keys S1.... Sn.

This what I have tried so far:

```<code>b = a.pop('Scores')
c = list(b.values())
df = pd.DataFrame(c)
</code>```

This displays my dataframe as:

```<code>                                               0  \
0  {'Math': '95', 'Science': '74.5', 'English': '...
1  {'Math': '67.2', 'Science': '74.2', 'English':...

                                               1
0  {'Math': '87.9', 'Science': '97.3', 'English':...
1                                               None
</code>```

Instead, I am looking for:

```<code>Math  Science  English
95    74.5     60.5
87.9  97.3     78.3
67.2  74.2     89
</code>```

I would appreciate any help I can get.

答:
You can use sum after iterating over the values of the dict.

Code:

```<code>import pandas as pd

data = sum([x for x in a['Scores'].values()], [])
print(pd.DataFrame(data, columns=['Math', 'Science', 'English']))
</code>```

Test Data:

```<code>a = {'Scores': {'s1': [{'Math': '95',
                        'Science': '74.5',
                        'English': '60.5'},
                       {'Math': '87.9',
                        'Science': '97.3',
                        'English': '78.3'}],
                's2': [{'Math': '67.2',
                        'Science': '74.2',
                        'English': '89'}]}}
</code>```

Result:

```<code>   Math Science English
0  67.2    74.2      89
1    95    74.5    60.5
2  87.9    97.3    78.3
</code>```

Body:
Python beginner here. I am struggling to dump my list of dicts into a pandas.DataFrame the right away. My data has the following structure.

a = {'Scores': {'s1': [{'Math': '95',
'Science': '74.5',
'English': '60.5'},
{'Math': '87.9',
'Science': '97.3',
'English': '78.3'}],
's2': [{'Math': '67.2',
'Science': '74.2',
'English': '89'}]}}

My pandas.Dataframe columns should be the subjects 'Math', 'Science' and 'English' and the rows should be the scores. The columns are dynamically created so I can not explicitly mention the column names to call it. All I need are the values of keys S1.... Sn.

This what I have tried so far:

b = a.pop('Scores')
c = list(b.values())
df = pd.DataFrame(c)

This displays my dataframe as:

                                               0  \
0  {'Math': '95', 'Science': '74.5', 'English': '...
1  {'Math': '67.2', 'Science': '74.2', 'English':...

                                               1
0  {'Math': '87.9', 'Science': '97.3', 'English':...
1                                               None

Instead, I am looking for:

Math  Science  English
95    74.5     60.5
87.9  97.3     78.3
67.2  74.2     89

I would appreciate any help I can get.

Body:
You can use sum after iterating over the values of the dict.

Code:

import pandas as pd

data = sum([x for x in a['Scores'].values()], [])
print(pd.DataFrame(data, columns=['Math', 'Science', 'English']))

Test Data:

a = {'Scores': {'s1': [{'Math': '95',
                        'Science': '74.5',
                        'English': '60.5'},
                       {'Math': '87.9',
                        'Science': '97.3',
                        'English': '78.3'}],
                's2': [{'Math': '67.2',
                        'Science': '74.2',
                        'English': '89'}]}}

Result:

   Math Science English
0  67.2    74.2      89
1    95    74.5    60.5
2  87.9    97.3    78.3


问:
URL Beautification using .htaccess or php?
In search of a more userfriendly & search engine friendly urls, i want have beautied my urls:
The htacces apache rule that achieves this (Thanks to Laurence Gonsalves)

```<code>RewriteRule ^([a-z][a-z])/(.*) /$2?ln=$1 [L]
</code>```

which makes this possible:

/uk/somepage  instead of   /somepage?ln=uk

/de/somepage  instead of   /somepage?ln=de

/ja/somepage  instead of   /somepage?ln=ja

Now the difficult part: previously, the url was replaced with a normal link like href="?ln=de" or href="?ln=it" for changing language of the current page. But now how can i achieve that? Sothat the current page stays the same, but only the preceding two lowercase letters that say to the browser what language it is in change?

So how to tell the link to only change the /uk/contact to /de/contact once the german (de) language flag is clicked? php solution to rewrite the url or htaccess solutions are accepted.

I found out that $_SERVER['REQUEST_URI'] will output /uk/somepage but i cant write the php code that can split up the components, add a new language code like "de" into it, which i can put manually into a normal href that goes on a German flag. etc. Thanks for any and all clues/answers!

答:
You'd probably want to look at something like explode or regular expressions to strip out the non-language part of the URL (e.g., /contact) and just add it again to a new string containing the language identifier.

Maybe this could get you started:

```<code><?php

function changeLanguageLink($language_id)
{
    $uri = $_SERVER['REQUEST_URI'];

    $link = preg_replace('/\/?(uk|de)\/(.*)/', "/$2", $uri);
    $link = $language_id . $link;

    return $link;
}

?>

<a href="changeLanguage('uk');">Change language to UK</a>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In search of a more userfriendly & search engine friendly urls, i want have beautied my urls:
The htacces apache rule that achieves this (Thanks to Laurence Gonsalves)

RewriteRule ^([a-z][a-z])/(.*) /$2?ln=$1 [L]

which makes this possible:

/uk/somepage  instead of   /somepage?ln=uk

/de/somepage  instead of   /somepage?ln=de

/ja/somepage  instead of   /somepage?ln=ja

Now the difficult part: previously, the url was replaced with a normal link like href="?ln=de" or href="?ln=it" for changing language of the current page. But now how can i achieve that? Sothat the current page stays the same, but only the preceding two lowercase letters that say to the browser what language it is in change?

So how to tell the link to only change the /uk/contact to /de/contact once the german (de) language flag is clicked? php solution to rewrite the url or htaccess solutions are accepted.

I found out that $_SERVER['REQUEST_URI'] will output /uk/somepage but i cant write the php code that can split up the components, add a new language code like "de" into it, which i can put manually into a normal href that goes on a German flag. etc. Thanks for any and all clues/answers!

Body:
You'd probably want to look at something like explode or regular expressions to strip out the non-language part of the URL (e.g., /contact) and just add it again to a new string containing the language identifier.

Maybe this could get you started:

<?php

function changeLanguageLink($language_id)
{
    $uri = $_SERVER['REQUEST_URI'];

    $link = preg_replace('/\/?(uk|de)\/(.*)/', "/$2", $uri);
    $link = $language_id . $link;

    return $link;
}

?>

<a href="changeLanguage('uk');">Change language to UK</a>


问:
PHP files outside Codeigniter's application folder get 404 error
I recently moved a CodeIgniter site to a new server.  Everything is running fine but when attempting to run PHP files on the public folder I get a 404 error message.  This is my current structure:

```<code>public_html/
 |–– application/
 |–– public/
 |      |-sample.html
 |      |-simple.php
 |
 |–– system/
 |–– uploads/
 |-- .htaccess
 |–– index.php
</code>```

If I go example.com/public/sample.html I runs ok.  If I instead try  example.com/public/simple.php I get a 404 error.  I checked .htaccess but it seems ok and it was actually working ok on the previous server.

Just for illustration purposes this is the current .htaccess:

```<code>RewriteEngine on
RewriteBase /
RewriteCond $1 !^(index\.php|public|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
</code>```

I already tried a few solutions from SO but none some got me a 500 error, the rest didn't do anything.

答:
On your index.php line 132 if your using codeigniter 3 +</p>

```<code>/*
 *---------------------------------------------------------------
 * VIEW DIRECTORY NAME
 *---------------------------------------------------------------
 *
 * If you want to move the view directory out of the application
 * directory, set the path to it here. The directory can be renamed
 * and relocated anywhere on your server. If blank, it will default
 * to the standard location inside your application directory.
 * If you do move this, use an absolute (full) server path.
 *
 * NO TRAILING SLASH!
 */
    $view_folder = '';
</code>```

Body:
I recently moved a CodeIgniter site to a new server.  Everything is running fine but when attempting to run PHP files on the public folder I get a 404 error message.  This is my current structure:

public_html/
 |–– application/
 |–– public/
 |      |-sample.html
 |      |-simple.php
 |
 |–– system/
 |–– uploads/
 |-- .htaccess
 |–– index.php

If I go example.com/public/sample.html I runs ok.  If I instead try  example.com/public/simple.php I get a 404 error.  I checked .htaccess but it seems ok and it was actually working ok on the previous server.

Just for illustration purposes this is the current .htaccess:

RewriteEngine on
RewriteBase /
RewriteCond $1 !^(index\.php|public|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]

I already tried a few solutions from SO but none some got me a 500 error, the rest didn't do anything.

Body:
On your index.php line 132 if your using codeigniter 3 +

/*
 *---------------------------------------------------------------
 * VIEW DIRECTORY NAME
 *---------------------------------------------------------------
 *
 * If you want to move the view directory out of the application
 * directory, set the path to it here. The directory can be renamed
 * and relocated anywhere on your server. If blank, it will default
 * to the standard location inside your application directory.
 * If you do move this, use an absolute (full) server path.
 *
 * NO TRAILING SLASH!
 */
    $view_folder = '';


问:
SonarQube:java.lang.IllegalStateException: Webapp did not start
I was trying to deploy SonarQube at a local virtual Ubuntu machine.Everything was done.But when I use /etc/init.d/sonar start to start sonar server, it failed.

web.log:

```<code>`2017.03.29 01:33:04 WARN  web[][o.s.p.ProcessEntryPoint] Fail to start web
java.lang.IllegalStateException: Webapp did not start
    at org.sonar.server.app.EmbeddedTomcat.isUp(EmbeddedTomcat.java:83)
    at org.sonar.server.app.WebServer.isUp(WebServer.java:46)
    at org.sonar.process.ProcessEntryPoint.launch(ProcessEntryPoint.java:105)
    at org.sonar.server.app.WebServer.main(WebServer.java:67)
2017.03.29 01:33:05 INFO  web[][o.s.s.a.TomcatAccessLog] Web server is stopped
`
</code>```

Below are my versions:

Java : JDK1.8

SonarQube : 6.3

Sonar-Runner:2.4

Mysql : 5.7

full web.log:

```<code>    2017.03.29 01:33:04 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [ROOT] appears to have started a thread named [elasticsearch[Piledriver][transport_client_timer][T#1]{Hashed wheel timer #1}] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.lang.Thread.sleep(Native Method)
 org.jboss.netty.util.HashedWheelTimer$Worker.waitForNextTick(HashedWheelTimer.java:445)
 org.jboss.netty.util.HashedWheelTimer$Worker.run(HashedWheelTimer.java:364)
 org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
 java.lang.Thread.run(Thread.java:745)
2017.03.29 01:33:04 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [ROOT] appears to have started a thread named [elasticsearch[Piledriver][generic][T#1]] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 sun.misc.Unsafe.park(Native Method)
 java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
 java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
 java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
 java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)
 java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1066)
 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
 java.lang.Thread.run(Thread.java:745)
2017.03.29 01:33:04 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [ROOT] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.lang.Object.wait(Native Method)
 java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
 com.mysql.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:43)
2017.03.29 01:33:04 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [ROOT] appears to have started a thread named [Timer-0] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.lang.Object.wait(Native Method)
 java.util.TimerThread.mainLoop(Timer.java:552)
 java.util.TimerThread.run(Timer.java:505)
2017.03.29 01:33:04 INFO  web[][o.s.s.a.TomcatAccessLog] Web server is started
2017.03.29 01:33:04 INFO  web[][o.s.s.a.EmbeddedTomcat] HTTP connector enabled on port 9000
2017.03.29 01:33:04 WARN  web[][o.s.p.ProcessEntryPoint] Fail to start web
java.lang.IllegalStateException: Webapp did not start
    at org.sonar.server.app.EmbeddedTomcat.isUp(EmbeddedTomcat.java:83)
    at org.sonar.server.app.WebServer.isUp(WebServer.java:46)
    at org.sonar.process.ProcessEntryPoint.launch(ProcessEntryPoint.java:105)
    at org.sonar.server.app.WebServer.main(WebServer.java:67)
2017.03.29 01:33:05 INFO  web[][o.s.s.a.TomcatAccessLog] Web server is stopped
</code>```

答: I checked it again,and found that i missed setting {SONAR_RUNNER_HOME}/binon My PATH.

Body:
I was trying to deploy SonarQube at a local virtual Ubuntu machine.Everything was done.But when I use /etc/init.d/sonar start to start sonar server, it failed.

web.log:

`2017.03.29 01:33:04 WARN  web[][o.s.p.ProcessEntryPoint] Fail to start web
java.lang.IllegalStateException: Webapp did not start
    at org.sonar.server.app.EmbeddedTomcat.isUp(EmbeddedTomcat.java:83)
    at org.sonar.server.app.WebServer.isUp(WebServer.java:46)
    at org.sonar.process.ProcessEntryPoint.launch(ProcessEntryPoint.java:105)
    at org.sonar.server.app.WebServer.main(WebServer.java:67)
2017.03.29 01:33:05 INFO  web[][o.s.s.a.TomcatAccessLog] Web server is stopped
`

Below are my versions:

Java : JDK1.8

SonarQube : 6.3

Sonar-Runner:2.4

Mysql : 5.7

full web.log:

    2017.03.29 01:33:04 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [ROOT] appears to have started a thread named [elasticsearch[Piledriver][transport_client_timer][T#1]{Hashed wheel timer #1}] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.lang.Thread.sleep(Native Method)
 org.jboss.netty.util.HashedWheelTimer$Worker.waitForNextTick(HashedWheelTimer.java:445)
 org.jboss.netty.util.HashedWheelTimer$Worker.run(HashedWheelTimer.java:364)
 org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
 java.lang.Thread.run(Thread.java:745)
2017.03.29 01:33:04 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [ROOT] appears to have started a thread named [elasticsearch[Piledriver][generic][T#1]] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 sun.misc.Unsafe.park(Native Method)
 java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
 java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(SynchronousQueue.java:460)
 java.util.concurrent.SynchronousQueue$TransferStack.transfer(SynchronousQueue.java:362)
 java.util.concurrent.SynchronousQueue.poll(SynchronousQueue.java:941)
 java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1066)
 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
 java.lang.Thread.run(Thread.java:745)
2017.03.29 01:33:04 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [ROOT] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.lang.Object.wait(Native Method)
 java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
 com.mysql.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:43)
2017.03.29 01:33:04 WARN  web[][o.a.c.l.WebappClassLoaderBase] The web application [ROOT] appears to have started a thread named [Timer-0] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
 java.lang.Object.wait(Native Method)
 java.util.TimerThread.mainLoop(Timer.java:552)
 java.util.TimerThread.run(Timer.java:505)
2017.03.29 01:33:04 INFO  web[][o.s.s.a.TomcatAccessLog] Web server is started
2017.03.29 01:33:04 INFO  web[][o.s.s.a.EmbeddedTomcat] HTTP connector enabled on port 9000
2017.03.29 01:33:04 WARN  web[][o.s.p.ProcessEntryPoint] Fail to start web
java.lang.IllegalStateException: Webapp did not start
    at org.sonar.server.app.EmbeddedTomcat.isUp(EmbeddedTomcat.java:83)
    at org.sonar.server.app.WebServer.isUp(WebServer.java:46)
    at org.sonar.process.ProcessEntryPoint.launch(ProcessEntryPoint.java:105)
    at org.sonar.server.app.WebServer.main(WebServer.java:67)
2017.03.29 01:33:05 INFO  web[][o.s.s.a.TomcatAccessLog] Web server is stopped


问:
Python - Read all files in a folder and create unique output for each file
I'm trying to split two huge source files (with corresponding content in each line) into several smaller files with each containing unique input but so far, things have been off. I was thinking to have a method read all files in an  output directory and join their content into a certain blacklist. So at first, this blacklist is empty as the files are empty and I want to read the source file and copy n lines into the first smaller file and add the content to the blacklist. Next, I'm checking the list and write lines to the second file n times only if they're not on said blacklist. For some reason, I am not getting any input to the blacklist after I appended what was read the first time.
Here's what I got:

```<code>def check_overlap(path):
# check if lines appear in other files

    content = []
    for filename in os.listdir(path):
        with open(path + filename, "r", encoding="utf-8") as f:
            content.append(f.read())
            print(filename + str(content))
            # when I print this out, it's empty for the first file
            # the other 3 files have the desired output, but why?
            # How is it empty after I appended the content of f?
            f.close()

    all_content = "".join(content)
    return all_content

def shuffle_data(n, source, output):
# shuffle source into n portions while keeping each line unique

    with open(output, "w", encoding="utf-8") as shuffled_file:

        existing_files = check_overlap()

        with open(source, 'r', encoding="utf-8") as source:
            i = 0
            for line in source:
                if i < n and line not in existing_files:
                    shuffled_file.write(line)
                    i += 1

shuffle_data(50, "source1", "output_50A")
shuffle_data(50, "source2", "output_50B")
shuffle_data(200, "source1", "output_200A")
shuffle_data(200, "source2", "output_200B")
</code>```

This also means I'm getting the wrong output overall. The sources look like this:

```<code>File 1    File 2
dog       dogs
book      books
horse     horses
flower    flowers
egg       eggs
</code>```

And they have to keep their corresponding lines but because of the error I'm getting:

```<code>Output 1    Output 2
dog         dogs
book        books
horse       flowers
flowers     eggs
</code>```

So it seems to be skipping random lines because of the wonky blacklist. The sources are randomized everytime I run the program so it's always different at which line they start to diverge. All output files are in the same directory, sources are in a different one.

答:
Based on the comments, try something like this. You may need to handle exceptions if the source files run out before the sizes do.</p>

```<code>Sizes = [50, 100, 200, 600, 1000, 3000, 10000]

with open('file1') as f1:
    with open('file2') as f2:
        sources = iter(zip(f1, f2))

        for size in Sizes:
            o1_name = 'output_{}A'.format(size)
            o2_name = 'output_{}B'.format(size)
            with open(o1_name, 'w') as o1:
                with open(o2_name, 'w') as o2:
                    for _ in range(size):
                        l1,l2 = next(sources)
                        o1.write(l1.strip())
                        o2.write(l2.strip())
</code>```

Body:
I'm trying to split two huge source files (with corresponding content in each line) into several smaller files with each containing unique input but so far, things have been off. I was thinking to have a method read all files in an  output directory and join their content into a certain blacklist. So at first, this blacklist is empty as the files are empty and I want to read the source file and copy n lines into the first smaller file and add the content to the blacklist. Next, I'm checking the list and write lines to the second file n times only if they're not on said blacklist. For some reason, I am not getting any input to the blacklist after I appended what was read the first time.
Here's what I got:

def check_overlap(path):
# check if lines appear in other files

    content = []
    for filename in os.listdir(path):
        with open(path + filename, "r", encoding="utf-8") as f:
            content.append(f.read())
            print(filename + str(content))
            # when I print this out, it's empty for the first file
            # the other 3 files have the desired output, but why?
            # How is it empty after I appended the content of f?
            f.close()

    all_content = "".join(content)
    return all_content

def shuffle_data(n, source, output):
# shuffle source into n portions while keeping each line unique

    with open(output, "w", encoding="utf-8") as shuffled_file:

        existing_files = check_overlap()

        with open(source, 'r', encoding="utf-8") as source:
            i = 0
            for line in source:
                if i < n and line not in existing_files:
                    shuffled_file.write(line)
                    i += 1

shuffle_data(50, "source1", "output_50A")
shuffle_data(50, "source2", "output_50B")
shuffle_data(200, "source1", "output_200A")
shuffle_data(200, "source2", "output_200B")

This also means I'm getting the wrong output overall. The sources look like this:

File 1    File 2
dog       dogs
book      books
horse     horses
flower    flowers
egg       eggs

And they have to keep their corresponding lines but because of the error I'm getting:

Output 1    Output 2
dog         dogs
book        books
horse       flowers
flowers     eggs

So it seems to be skipping random lines because of the wonky blacklist. The sources are randomized everytime I run the program so it's always different at which line they start to diverge. All output files are in the same directory, sources are in a different one.

Body:
Based on the comments, try something like this. You may need to handle exceptions if the source files run out before the sizes do.

Sizes = [50, 100, 200, 600, 1000, 3000, 10000]

with open('file1') as f1:
    with open('file2') as f2:
        sources = iter(zip(f1, f2))

        for size in Sizes:
            o1_name = 'output_{}A'.format(size)
            o2_name = 'output_{}B'.format(size)
            with open(o1_name, 'w') as o1:
                with open(o2_name, 'w') as o2:
                    for _ in range(size):
                        l1,l2 = next(sources)
                        o1.write(l1.strip())
                        o2.write(l2.strip())


问:
how to pass ID in a link using jquery
I have a book now button, when a user clicks on book now he should be redirected to a order confirmation page. I want to pass type and id in a url using jquery.
want to pass this kind of url - http://localhost/company/order-confirmation?type=course&id=35

How can I do that in jquery.

html:

```<code> <a href="" class="book_now" batch-id="">Book Now</a>
</code>```

Jquery:

```<code>  $('.book_now',template).attr('batch-id', val['batch_id']);
</code>```

答:
You can pass href in an anchor dynamically like:

```<code>$('.book_now').attr('href', 'url link');
</code>```

Title: how to pass ID in a link using jquery

Body:
I have a book now button, when a user clicks on book now he should be redirected to a order confirmation page. I want to pass type and id in a url using jquery.
want to pass this kind of url - http://localhost/company/order-confirmation?type=course&id=35

How can I do that in jquery.

html:

 Book Now

Jquery:

  $('.book_now',template).attr('batch-id', val['batch_id']);

Body:
You can pass href in an anchor dynamically like:

$('.book_now').attr('href', 'url link');


问:
Where do I save reference to list of GMSMarkers
I'm building an iOS application in Swift 3 which uses a list of GMSMarker displayed on a map in my ViewController. The list of markers is made from an array of my model Store

The code in mi ViewController is:

```<code>class ViewController: UIViewController {

    // MARK: - IBOutlets

    @IBOutlet weak var mapView: GMSMapView!
    @IBOutlet weak var tableView: UITableView!

    var stores: [Store]!

    override func viewDidLoad() {
        super.viewDidLoad()
        stores = Store.listStores()
    }

  ...
  ...
  ...
}
</code>```

I need to know the reference for those marker because I want to change their snippet info when something happens in the app.

The trouble is I don't know what is the best way to save the reference following the concept of MVC (Model, View, Controller), I'll going to explain the two options I've thought.

Create a global array in the ViewController, then call my function to create a GMSMarker for each store in the Store array and save it in the global array.

Import GoogleMaps in my Store class and create a GMSMarker property. In the init() initializes the GMSMarker and assign it to the created property. Doing it I'll always have a referenced to the marker therefore I think that is inefficient because the marker is only used in one ViewController but the Store object is used in different parts of the app

Which one is the best way ? Is there any other way to do it better ?

答: Try to add the relevant information about that marker into a custom structure or class that you could store into Store model, then you can create a method in your controller that return a built marker with the stored information. It's fine because you disconnect Google Services from your own models. So, if you should change Google Maps to other maps framework, you have to change the marker builder method only.</p>

Body:
I'm building an iOS application in Swift 3 which uses a list of GMSMarker displayed on a map in my ViewController. The list of markers is made from an array of my model Store

The code in mi ViewController is:

class ViewController: UIViewController {

    // MARK: - IBOutlets

    @IBOutlet weak var mapView: GMSMapView!
    @IBOutlet weak var tableView: UITableView!

    var stores: [Store]!

    override func viewDidLoad() {
        super.viewDidLoad()
        stores = Store.listStores()
    }

  ...
  ...
  ...
}

I need to know the reference for those marker because I want to change their snippet info when something happens in the app.

The trouble is I don't know what is the best way to save the reference following the concept of MVC (Model, View, Controller), I'll going to explain the two options I've thought.

Create a global array in the ViewController, then call my function to create a GMSMarker for each store in the Store array and save it in the global array.

Import GoogleMaps in my Store class and create a GMSMarker property. In the init() initializes the GMSMarker and assign it to the created property. Doing it I'll always have a referenced to the marker therefore I think that is inefficient because the marker is only used in one ViewController but the Store object is used in different parts of the app

Which one is the best way ? Is there any other way to do it better ?


答:
You can use data attribute for this task like

```<code> <a href="" class="book_now" data-id="11">Book Now</a>
</code>```

and in js code

```<code>var order_id= $('.book_now').data("id");
</code>```

But why using  here if you want to send data over jquery, i think its better to use button here.

Hope that helps.

Title: how to pass ID in a link using jquery

Body:
You can use data attribute for this task like

 <a href="" class="book_now" data-id="11">Book Now</a>

and in js code

var order_id= $('.book_now').data("id");

But why using  here if you want to send data over jquery, i think its better to use button here.

Hope that helps.


问:
How to mock a third party lib which only has concrete classes using Moq,Xunit
I am implementing a API which handles different communication between the application and the internet (WebSocket, Socket.IO, WebClient http requests..) the TDD way. Until now I was able to write unit tests for all the methods because I could encapsulate all the calls in order to to mock them. For example when one method uses a http request via the System.Net.Webclient I had full control by mocking the HttpWebResponse.

Now for the next request I have to use a third party library which, at the end just sends out http requests. The problem is that I have no idea how to mock that since all the classes are concrete (most sealed) classes. For the sake of simplification here is a short example.

This would be the method I want to unit test. It sends out a request and calls the callback depending on the response coming back from the request:

```<code>public void MyMethodIwantToUnitTest(string data, Action<SomeData> callback)
</code>```

The third party lib is quite straight forward, you build your request with a callback and send it out:

```<code>HTTPRequest request = new HTTPRequest(new Uri("https://google.com"), onRequestFinished);
request.Send();

 void OnRequestFinished(HTTPRequest request, HTTPResponse response)
{
 // here would be basically the logic I want to test
}
</code>```

What I need is to somehow call the onRequestFinished in my unity test,with a mock HTTPResponse (HttpResponse is just a concrete class).
And I have no idea if that is even possible.

答:
Here's my take on it.
The client code uses IResource.Fetch(url, callback)

Use a mocking framework create an IResource mock & invoke the callback with the required response/data, whenever it is called. Plug it into the calling code as a dependency.

The code in the last snippet in the question, moves inside the real IResource.Fetch implementation. Since this is at the edge, I normally use an integration test - that runs against the real network.
 If I have a type, whose responsibility is to serialize something to disk/database, I verify that with an integration test that goes full cycle.
Assumptions:

There isn't much logic in this type - it is a pass through to the concrete library.

Once it is implemented, this code isn't going to be modified frequently

Slower. Better confidence and also bypasses the untestable library issue. I tag them with an 'Integration' category and run these tests once before commit, not after every edit.

Body:
I am implementing a API which handles different communication between the application and the internet (WebSocket, Socket.IO, WebClient http requests..) the TDD way. Until now I was able to write unit tests for all the methods because I could encapsulate all the calls in order to to mock them. For example when one method uses a http request via the System.Net.Webclient I had full control by mocking the HttpWebResponse.

Now for the next request I have to use a third party library which, at the end just sends out http requests. The problem is that I have no idea how to mock that since all the classes are concrete (most sealed) classes. For the sake of simplification here is a short example.

This would be the method I want to unit test. It sends out a request and calls the callback depending on the response coming back from the request:

public void MyMethodIwantToUnitTest(string data, Action<SomeData> callback)

The third party lib is quite straight forward, you build your request with a callback and send it out:

HTTPRequest request = new HTTPRequest(new Uri("https://google.com"), onRequestFinished);
request.Send();

 void OnRequestFinished(HTTPRequest request, HTTPResponse response)
{
 // here would be basically the logic I want to test
}

What I need is to somehow call the onRequestFinished in my unity test,with a mock HTTPResponse (HttpResponse is just a concrete class).
And I have no idea if that is even possible.


问:
after save not direct to original page
This code is for save the data after key in form meeting. But when it's save it doesn't bring back to the original page.
It just showing blank page.  </p>

```<code>$datetime=date("Y-m-d H:i",strtotime($_POST['datetime']));
$type=$_POST['meeting_type'];
$bilno=$_POST['bilno'];
$total_agenda=$_POST['total_agenda'];
    $tablename="meeting_info";
    $sql_ins="INSERT INTO meeting_info(datetime, type, bilno, total_agenda) VALUES ( '$datetime','$type','$bilno', '$total_agenda')";
    $conn->query($sql_ins);

    $sql_id = "SELECT id FROM meeting_info ORDER BY id DESC LIMIT 1";
    $result = $conn->query($sql_id);

    if ($result->num_rows > 0)
    {
        // output data of each row
        if($row = $result->fetch_assoc())
        {
            $id=$row["id"];
            echo "<script type='text/javascript'>window.location.href='administration.php?id='.$id;</script>";
        }
    }
$conn->close();
</code>```

答:
you can do it like this

```<code>header("location:administration.php?id=".$id);
</code>```

instead of echoing the url

Title: after save not direct to original page

Body:
This code is for save the data after key in form meeting. But when it's save it doesn't bring back to the original page.
It just showing blank page.

$datetime=date("Y-m-d H:i",strtotime($_POST['datetime']));
$type=$_POST['meeting_type'];
$bilno=$_POST['bilno'];
$total_agenda=$_POST['total_agenda'];
    $tablename="meeting_info";
    $sql_ins="INSERT INTO meeting_info(datetime, type, bilno, total_agenda) VALUES ( '$datetime','$type','$bilno', '$total_agenda')";
    $conn->query($sql_ins);

    $sql_id = "SELECT id FROM meeting_info ORDER BY id DESC LIMIT 1";
    $result = $conn->query($sql_id);

    if ($result->num_rows > 0)
    {
        // output data of each row
        if($row = $result->fetch_assoc())
        {
            $id=$row["id"];
            echo "";
        }
    }
$conn->close();

Body:
you can do it like this

header("location:administration.php?id=".$id);

instead of echoing the url