问:
Jmeter- How to pass Comma separated String as 1 value through parametrization
From a csv file, I need to pass

224,329,429

as a single value to one of the parameter in HTTP request.
I have parameterized using CSV data config. But, only 224 is getting passed.

I want 224,329,429 to be treated as a single value.

Please let me know how do I achieve this. Should I change anything in CSV config or CSV file to make this work?

答:
Just use __StringFromFile() function instead of using CSV Data Set Config.

The __StringFromFile() function reads next line from the file each time it's being called so it seems to be a lot easier to stick to it for particular your scenario.

The syntax is as simple as ${__StringFromFile(/path/to/your/file.csv,,,)} and the function can be used anywhere in the script, i.e. directly in the request parameter section.

See Apache JMeter Functions - An Introduction to get started with the JMeter Functions concept and comprehensive information on the above and other JMeter functions.


来源: stackexchange

问:
IF NOT EXIST Recored Select Some Data
I wrote a query that selects highest record from tbl. I want check if there is no record in tbl my query return fake data like (StudentId = 1,HighScore=0)

```<code>var queryWin = (from T in ((from tbl_ActPoints in dc.tbl_ActPoints
                select new
                {
                    tbl_ActPoints.StudentId,
                    tbl_ActPoints.Score
                }))
    group T by new
    {
        T.StudentId
    } into g
    orderby
      ((System.Int32?)g.Sum(p => p.Score) ?? (System.Int32?)0) descending
    select new
    {
        g.Key.StudentId,
        HighScore = ((System.Int32?)g.Sum(p => p.Score) ?? (System.Int32?)0)
    }).Take(1);
</code>```

答:
Try this:</p>

```<code>var queryWin = (from T in ((from tbl_ActPoints in dc.tbl_ActPoints
                select new
                {
                    tbl_ActPoints.StudentId,
                    tbl_ActPoints.Score
                }))
    group T by new
    {
        T.StudentId
    } into g
    orderby
      ((System.Int32?)g.Sum(p => p.Score) ?? (System.Int32?)0) descending
    select new
    {
        g.Key.StudentId,
        HighScore = ((System.Int32?)g.Sum(p => p.Score) ?? (System.Int32?)0)
    }).Take(1);

var result = queryWin.FirstOrDefault();

if (result == null)
  result = new { StudentId = 1, HighScore=0 };
</code>```

ContentLicense: CC BY-SA 3.0

Title: IF NOT EXIST Recored Select Some Data

Body:
I wrote a query that selects highest record from tbl. I want check if there is no record in tbl my query return fake data like (StudentId = 1,HighScore=0)

var queryWin = (from T in ((from tbl_ActPoints in dc.tbl_ActPoints
                select new
                {
                    tbl_ActPoints.StudentId,
                    tbl_ActPoints.Score
                }))
    group T by new
    {
        T.StudentId
    } into g
    orderby
      ((System.Int32?)g.Sum(p => p.Score) ?? (System.Int32?)0) descending
    select new
    {
        g.Key.StudentId,
        HighScore = ((System.Int32?)g.Sum(p => p.Score) ?? (System.Int32?)0)
    }).Take(1);

Body:
Try this:

var queryWin = (from T in ((from tbl_ActPoints in dc.tbl_ActPoints
                select new
                {
                    tbl_ActPoints.StudentId,
                    tbl_ActPoints.Score
                }))
    group T by new
    {
        T.StudentId
    } into g
    orderby
      ((System.Int32?)g.Sum(p => p.Score) ?? (System.Int32?)0) descending
    select new
    {
        g.Key.StudentId,
        HighScore = ((System.Int32?)g.Sum(p => p.Score) ?? (System.Int32?)0)
    }).Take(1);

var result = queryWin.FirstOrDefault();

if (result == null)
  result = new { StudentId = 1, HighScore=0 };


问:
Web page can't retrieve data from remote server in Phonegap (but works fine in Chrome)
I am trying to create an Android application using Phonegap 3.1. The app needs to retrieve data from my remote server, which is running Apache with the Header set Access-Control-Allow-Origin "*" directive set for the URI the app should be pulling data from. I have <access subdomains='true' url='*' /> set in Phonegap's config.xml file. The code below works and runs the "success" function if I put the web page into a local Apache directory separate from the server (different machines on different domains in different physical locations) and call it from Chrome, but when I try to call it via Phonegap it throws a less than helpful error of {"readystste":0,"responseText":"","status":0,"statusText":"error"}. The "readystate":0 looks like it might be an access or cross-site scripting error that's only happening in Phonegap, so I'm willing to believe it's something I need to configure on my end, but I'm going nuts trying to figure out what.

Thanks for any help you can provide. I need to get this running and have been scouring the web for a week trying to get it to work.

```<code><!DOCTYPE HTML>
<HTML>
<HEAD>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <link rel="stylesheet" type="text/css" href="css/affirmation.css">
  <script src="js/jquery-1.10.1.min.js"></script>
  <script>

  $.support.cors = true;

  $(document).ready(function(){

      $.ajax({
        type: 'POST',
        url: 'http://www.remote.server/info/API',
        datatype: 'json',
        data: JSON.stringify(
          { method: 'content',
          params: [
            'text passed to function on server'
          ],
          id: '1' }
        ),
        success: function(response, textstatus, jqxhr) {
        $('#graf1').text(JSON.stringify(response));
        $('#graf3').text(JSON.stringify(textstatus));
        $('#graf6').text(JSON.stringify(jqxhr));
        },
        error: function(jqxhr, textstatus, errorthrown) {
        $('#graf1').text(JSON.stringify(jqxhr));
        $('#graf3').text(JSON.stringify(textstatus));
        $('#graf6').text(JSON.stringify(errorthrown));
        }

      });
  });

  </script>

</HEAD>
<BODY>
  <DIV ID="header">JSON Server Test</DIV>
  <DIV ID="content">
  <DIV ID="graf1" CLASS="bodytext"></DIV>
  <DIV ID="graf3" CLASS="bodytext"></DIV>
  <DIV ID="graf6" CLASS="bodytext"></DIV>
</BODY>
</HTML>
</code>```

答:
I tried everything including <access origin="*" subdomains="true" /> but din't work for me.

then I added

```<code><plugin name="cordova-plugin-whitelist" source="npm" spec="~1.2.1" />
</code>```

In my config.xml and it worked.

Body:
I am trying to create an Android application using Phonegap 3.1. The app needs to retrieve data from my remote server, which is running Apache with the Header set Access-Control-Allow-Origin "*" directive set for the URI the app should be pulling data from. I have <access subdomains='true' url='*' /> set in Phonegap's config.xml file. The code below works and runs the "success" function if I put the web page into a local Apache directory separate from the server (different machines on different domains in different physical locations) and call it from Chrome, but when I try to call it via Phonegap it throws a less than helpful error of {"readystste":0,"responseText":"","status":0,"statusText":"error"}. The "readystate":0 looks like it might be an access or cross-site scripting error that's only happening in Phonegap, so I'm willing to believe it's something I need to configure on my end, but I'm going nuts trying to figure out what.

Thanks for any help you can provide. I need to get this running and have been scouring the web for a week trying to get it to work.

<!DOCTYPE HTML>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <link rel="stylesheet" type="text/css" href="css/affirmation.css">

JSON Server Test

Body:
I tried everything including <access origin="*" subdomains="true" /> but din't work for me.

then I added

<plugin name="cordova-plugin-whitelist" source="npm" spec="~1.2.1" />

In my config.xml and it worked.


问:
How do I Serialize object to json using json.net which contains an image property
I have an object with a number of public properties where one is of type image.  I am trying to serialise this using json.net and assume that I will need to base64 encode this and serialise the resultant string.  I have tried with the BinaryConverter against the property without success below

```<code>public class Person
{
    public string name { get; set; }

    public int age { get; set; }

    [JsonConverter(typeof(BinaryConverter))]
    public Image photo { get; set; }

    public string ToJson()
    {
        return JsonConvert.SerializeObject(this);
    }
}
</code>```

When called with this test code...

```<code>var p = new Person();
p.name = "John Doe";
p.age = 99;
p.photo = Image.FromFile(@"dea4007a-c812-41e9-b09a-c7793c6e853d.jpg");

var json = p.ToJson();
Console.WriteLine(json);
Console.ReadKey();
</code>```

I get an exception "Unexpected value type when writing binary".  Any help would be very helpful as I have been searching the web for a while now without success.

答:
Json.NET has no idea about what is Image, so you have to help it a bit, for example by using a converter (BinaryConverter is not for images):

```<code>public class ImageConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
        var base64 = (string)reader.Value;
        // convert base64 to byte array, put that into memory stream and feed to image
        return Image.FromStream(new MemoryStream(Convert.FromBase64String(base64)));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
        var image = (Image) value;
        // save to memory stream in original format
        var ms = new MemoryStream();
        image.Save(ms, image.RawFormat);
        byte[] imageBytes = ms.ToArray();
        // write byte array, will be converted to base64 by JSON.NET
        writer.WriteValue(imageBytes);
    }

    public override bool CanConvert(Type objectType) {
        return objectType == typeof(Image);
    }
}

public class Person
{
    public string name { get; set; }

    public int age { get; set; }

    [JsonConverter(typeof(ImageConverter))]
    public Image photo { get; set; }

    public string ToJson()
    {
        return JsonConvert.SerializeObject(this);
    }
}
</code>```

Then it will both serialize and deserialize your class just fine.

Body:
I have an object with a number of public properties where one is of type image.  I am trying to serialise this using json.net and assume that I will need to base64 encode this and serialise the resultant string.  I have tried with the BinaryConverter against the property without success below

public class Person
{
    public string name { get; set; }

    public int age { get; set; }

    [JsonConverter(typeof(BinaryConverter))]
    public Image photo { get; set; }

    public string ToJson()
    {
        return JsonConvert.SerializeObject(this);
    }
}

When called with this test code...

var p = new Person();
p.name = "John Doe";
p.age = 99;
p.photo = Image.FromFile(@"dea4007a-c812-41e9-b09a-c7793c6e853d.jpg");

var json = p.ToJson();
Console.WriteLine(json);
Console.ReadKey();

I get an exception "Unexpected value type when writing binary".  Any help would be very helpful as I have been searching the web for a while now without success.

Body:
Json.NET has no idea about what is Image, so you have to help it a bit, for example by using a converter (BinaryConverter is not for images):

public class ImageConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
        var base64 = (string)reader.Value;
        // convert base64 to byte array, put that into memory stream and feed to image
        return Image.FromStream(new MemoryStream(Convert.FromBase64String(base64)));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
        var image = (Image) value;
        // save to memory stream in original format
        var ms = new MemoryStream();
        image.Save(ms, image.RawFormat);
        byte[] imageBytes = ms.ToArray();
        // write byte array, will be converted to base64 by JSON.NET
        writer.WriteValue(imageBytes);
    }

    public override bool CanConvert(Type objectType) {
        return objectType == typeof(Image);
    }
}

public class Person
{
    public string name { get; set; }

    public int age { get; set; }

    [JsonConverter(typeof(ImageConverter))]
    public Image photo { get; set; }

    public string ToJson()
    {
        return JsonConvert.SerializeObject(this);
    }
}

Then it will both serialize and deserialize your class just fine.


问:
How can I color text in
 that it contains in a

How to color a text in a
 that it contains in a
 when the user hovers with the mouse.

Suppose  I have this html code:

```<code><div id="riga_ristorante_1" >
<div>
  <p>HI</p>
</div>
<div><p>HOME</p></div>
<div><p>DOG</p></div>
</div>
</code>```

I want color the "hi","HOME","DOG" in black when the user go on the
 element, so I use CSS:

```<code>#riga_ristorante_1:hover > p {
     text-align: center;
     color: black;

}
</code>```

But it doesn't work. Anyone can help me?

答:
You have your p as second level in deep, so you can't use > as it applies to first level only. Use

```<code>#riga_ristorante_1:hover p {
     color: red;
}
</code>```

#riga_ristorante_1:hover p {
     color: red;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="riga_ristorante_1" >
<div>
  <p>HI</p>
</div>
<div><p>HOME</p></div>
<div><p>DOG</p></div>
</div></code>```

Title: How can I color text in <p> that it contains in a <div>

Body:
How to color a text in a
 that it contains in a
 when the user hovers with the mouse.

Suppose  I have this html code:

HI

HOME

DOG

I want color the "hi","HOME","DOG" in black when the user go on the
 element, so I use CSS:

#riga_ristorante_1:hover > p {
     text-align: center;
     color: black;

}

But it doesn't work. Anyone can help me?

Body:
You have your p as second level in deep, so you can't use > as it applies to first level only. Use

#riga_ristorante_1:hover p {
     color: red;
}

#riga_ristorante_1:hover p {
     color: red;

}

<div id="riga_ristorante_1" >
<div>
  <p>HI</p>
</div>
<div><p>HOME</p></div>
<div><p>DOG</p></div>
</div>


问:
C++ mix new/delete between libs?
If I use the new keyword in my library (which is built differently than my main app), when I delete it in my main app with delete, is there a chance that I may get a crash/error?

答:
It is a problem that I have only seen on Windows.

The Unixish systems do not make a habit of forcing shared libraries to link to different versions of the same library within the same program and all loaded symbols are visible globally.  That means that if an object is allocated in one part of code and deleted in another, both are using the same system library to do it.

I have to say, this problem Windows creates with its various C runtime DLLs is really annoying and unnatural to a C programmer.  Look at the C library; it has functions like strdup that malloc the string and expect the programmer to call free() on it.  But do the same thing in your own library on Windows and just wait for the explosion.  You'll have to wait, too, because it won't happen during development but only after you've given the compiled DLL to some other poor sap.

Title: C++ mix new/delete between libs?

OwnerDisplayName: Zan Lynx

ContentLicense: CC BY-SA 2.5


问:
how to disable some key like @,!%" and compatible in ie and FF?
sorry if my english bad..

let's to the point

here my HTML:

```<code><input type="text" name="hostname" onkeypress="return keyPressHostName(event)">
</code>```

and this my JS:

```<code>function keyPressHostName(e) {
    var input = e.keyCode ? e.keyCode : e.charCode;
    if ((input >= 48 && input <= 57) // 0-9
    || (input >= 65 && input <= 90) //a-z
    || (input >= 97 && input <= 122) //A-Z
    || (input == 45) // dash (-)
    || (input == 46) // point(.)
    || (input == 37) // left key (<-)
    || (input == 39) // right key (->)
    || (input == 8) // backspace
    || (input == 9) // tab
    )
        return true;
    else
        return false;
}
/*alert(input);
    if ((e.keyCode==45)||(e.keyCode==46)||(e.keyCode==37)||(e.keyCode==39)||(e.keyCode==8)||(e.keyCode==9)||(e.keyCode==39))
        return true;
    else if ((e.charCode>=48 && e.charCode<=57)||(e.charCode>=65 && e.charCode<=90)||(e.charCode>=97 && e.charCode<=122)||e.charCode==45||e.charCode==46)
        return true;
    else
        return false;
*/
</code>```

but there are some error

the % (percent key) return true... and when i traced it. percent key is 37, same as left key

in IE, when user press left,right,backspace, or delete... the cursor move to end

anyone can suggest me a better way?

in my text field there only can receive 0-9,a-z,A-Z,dash,and point,...

答:
@Eric Fortis: i've discuss to my teacher and he said keyCode or charCode in Opera,IE,FireFox etc is different....

so my script like this

```<code><input type="text" name="hostname" onkeypress="return keyPressHostName(event)">
</code>```

and the js like this:

```<code>function keyPressHostName(e)
{
    if (navigator.appName=="Opera")
    {
        var c= String.fromCharCode(e.keyCode);
        if ((e.keyCode==37)// left
            ||(e.keyCode==8)// <== backspace
            ||(e.keyCode==9)// tab
            ||(e.keyCode==39)// right
        )return true;
        else if (/\_/.test(c))return false;
        else if (/[\w\-\.]/.test(c))return true;
        else return false;
    }
    else if (navigator.appName =="Netscape")
    {
        var c= String.fromCharCode(e.charCode);
        if (/\_/.test(c))return false;
        else if (/[\w\-\.]/.test(c))return true;
        else if (e.keyCode>=1)return true;
        else return false;
    }
    else if (/Microsoft/.test(navigator.appName)){
        var c= String.fromCharCode(e.keyCode);
        if (/\_/.test(c))return false;
        else if (/[\w\-\.]/.test(c))return true;
        else return false;
    }
    else
    {
        var CharKey = (e.keyCode)?e.keyCode:e.charCode;
        var c= String.fromCharCode(CharKey);
        if (/\_/.test(c))return false;
        else if (/[\w\-\.]/.test(c))return true;
        else return false;
    }
}
</code>```

i also found this JavaScript KeyCode vs CharCode

Body:
sorry if my english bad..

let's to the point

here my HTML:

<input type="text" name="hostname" onkeypress="return keyPressHostName(event)">

and this my JS:

function keyPressHostName(e) {
    var input = e.keyCode ? e.keyCode : e.charCode;
    if ((input >= 48 && input <= 57) // 0-9
    || (input >= 65 && input <= 90) //a-z
    || (input >= 97 && input <= 122) //A-Z
    || (input == 45) // dash (-)
    || (input == 46) // point(.)
    || (input == 37) // left key (<-)
    || (input == 39) // right key (->)
    || (input == 8) // backspace
    || (input == 9) // tab
    )
        return true;
    else
        return false;
}
/*alert(input);
    if ((e.keyCode==45)||(e.keyCode==46)||(e.keyCode==37)||(e.keyCode==39)||(e.keyCode==8)||(e.keyCode==9)||(e.keyCode==39))
        return true;
    else if ((e.charCode>=48 && e.charCode<=57)||(e.charCode>=65 && e.charCode<=90)||(e.charCode>=97 && e.charCode<=122)||e.charCode==45||e.charCode==46)
        return true;
    else
        return false;
*/

but there are some error

the % (percent key) return true... and when i traced it. percent key is 37, same as left key

in IE, when user press left,right,backspace, or delete... the cursor move to end

anyone can suggest me a better way?

in my text field there only can receive 0-9,a-z,A-Z,dash,and point,...

Body:
@Eric Fortis: i've discuss to my teacher and he said keyCode or charCode in Opera,IE,FireFox etc is different....

so my script like this

<input type="text" name="hostname" onkeypress="return keyPressHostName(event)">

and the js like this:

function keyPressHostName(e)
{
    if (navigator.appName=="Opera")
    {
        var c= String.fromCharCode(e.keyCode);
        if ((e.keyCode==37)// left
            ||(e.keyCode==8)// <== backspace
            ||(e.keyCode==9)// tab
            ||(e.keyCode==39)// right
        )return true;
        else if (/\_/.test(c))return false;
        else if (/[\w\-\.]/.test(c))return true;
        else return false;
    }
    else if (navigator.appName =="Netscape")
    {
        var c= String.fromCharCode(e.charCode);
        if (/\_/.test(c))return false;
        else if (/[\w\-\.]/.test(c))return true;
        else if (e.keyCode>=1)return true;
        else return false;
    }
    else if (/Microsoft/.test(navigator.appName)){
        var c= String.fromCharCode(e.keyCode);
        if (/\_/.test(c))return false;
        else if (/[\w\-\.]/.test(c))return true;
        else return false;
    }
    else
    {
        var CharKey = (e.keyCode)?e.keyCode:e.charCode;
        var c= String.fromCharCode(CharKey);
        if (/\_/.test(c))return false;
        else if (/[\w\-\.]/.test(c))return true;
        else return false;
    }
}

i also found this JavaScript KeyCode vs CharCode


问:
Selected value for DropDownList not showing
I'm trying to set a selected value for my dropdownlist but I can't make it show on page.

This is how I set the selected value;

```<code>productHier = new SelectList(hierarchyList, "ProductHierarchyID", "ProductHierarchyCode", orderline.PrmProductVariant.PrmProduct.PrmProductHierarchy1 );
ViewBag.productHier = productHier;
</code>```

and this is the part in my View

```<code>@Html.DropDownList("Hierarchy", (IEnumerable<SelectListItem>)ViewBag.productHier, "Hierarchy Seçiniz", new { @Class = "form-control control-text" })
</code>```

I tried many suggestions from other question on this subject but none helped me. I wonder what I'm missing.

EDIT: When I debug, I can see the values designated as selected value in controller and view but somehow I can't see them on page.

答:
To bind Hierarchy value you need use DropDownListFor HtmlHelper as below:

```<code>@Html.DropDownListFor(m=>m.Hierarchy, (IEnumerable<SelectListItem>)ViewBag.productHier, "Hierarchy Seçiniz", new { @Class = "form-control control-text" })
</code>```

You must have Hierarchy property set in controller when you return View.

Body:
I'm trying to set a selected value for my dropdownlist but I can't make it show on page.

This is how I set the selected value;

productHier = new SelectList(hierarchyList, "ProductHierarchyID", "ProductHierarchyCode", orderline.PrmProductVariant.PrmProduct.PrmProductHierarchy1 );
ViewBag.productHier = productHier;

and this is the part in my View

@Html.DropDownList("Hierarchy", (IEnumerable<SelectListItem>)ViewBag.productHier, "Hierarchy Seçiniz", new { @Class = "form-control control-text" })

I tried many suggestions from other question on this subject but none helped me. I wonder what I'm missing.

EDIT: When I debug, I can see the values designated as selected value in controller and view but somehow I can't see them on page.

Body:
To bind Hierarchy value you need use DropDownListFor HtmlHelper as below:

@Html.DropDownListFor(m=>m.Hierarchy, (IEnumerable<SelectListItem>)ViewBag.productHier, "Hierarchy Seçiniz", new { @Class = "form-control control-text" })

You must have Hierarchy property set in controller when you return View.


问:
How to make div bottom
I dont know how to name this topic properly.

When i set position:absolute; to the div,and set bottom:0; my div content goes to end of the page

I want to know how to make that div go to the end of the div In which it is located.

答:
You should not use 0 for bottom property because if it is then your content may be get off because HTML inline is vertical not horizontal so you will not be able to see your if bottom is 0.</p>

 I am not at bottom

Title: How to make div bottom

Body:
You should not use 0 for bottom property because if it is then your content may be get off because HTML inline is vertical not horizontal so you will not be able to see your if bottom is 0.

 I am not at bottom


问:
How to use Flasgger with Flask applications using Blueprints?
I am adding Swagger UI to my Python Flask application using Flasgger. Most common examples on the Internet are for the basic Flask style using @app.route:

```<code>from flasgger.utils import swag_from

@app.route('/api/<string:username>')
@swag_from('path/to/external_file.yml')
def get(username):
    return jsonify({'username': username})
</code>```

That works.

In my application however, I am not using @app.route decorators to define the endpoints. I am using flask Blueprints. Like following:

```<code>from flask import Flask, Blueprint
from flask_restful import Api, Resource
from flasgger.utils import swag_from
...

class TestResourceClass(Resource):

      @swag_from('docs_test_get.yml', endpoint='test')
      def get() :
         print "This is the get method for GET /1.0/myapi/test endpoint"

app = Flask(__name__)
my_api_blueprint = Blueprint('my_api', __name__)
my_api = Api(my_api_blueprint)

app.register_blueprint(my_api_blueprint, url_prefix='/1.0/myapi/')

my_api.add_resource(TestResourceClass, '/test/'
                        endpoint='test',
                        methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
....
</code>```

As seen above, I used @swag_from decorator on the TestResourceClass.get() method which is bound to the GET method endpoint. I also have the endpoint=test  matching in the two places.

But I am not getting anything on the Swagger UI, it is all blank. The docs_test_get.yml file does contain the valid yaml markup to define the swagger spec.

What am I missing? How can I get Flasgger Swagger UI working with Flask Blueprint based setup?

答:
Now there is an example of blueprint app in https://github.com/rochacbruno/flasgger/blob/master/examples/example_blueprint.py</p>

```<code>"""
A test to ensure routes from Blueprints are swagged as expected.
"""
from flask import Blueprint, Flask, jsonify

from flasgger import Swagger
from flasgger.utils import swag_from

app = Flask(__name__)

example_blueprint = Blueprint("example_blueprint", __name__)

@example_blueprint.route('/usernames/<username>', methods=['GET', 'POST'])
@swag_from('username_specs.yml', methods=['GET'])
@swag_from('username_specs.yml', methods=['POST'])
def usernames(username):
    return jsonify({'username': username})

@example_blueprint.route('/usernames2/<username>', methods=['GET', 'POST'])
def usernames2(username):
    """
    This is the summary defined in yaml file
    First line is the summary
    All following lines until the hyphens is added to description
    the format of the first lines until 3 hyphens will be not yaml compliant
    but everything below the 3 hyphens should be.
    ---
    tags:
      - users
    parameters:
      - in: path
        name: username
        type: string
        required: true
    responses:
      200:
        description: A single user item
        schema:
          id: rec_username
          properties:
            username:
              type: string
              description: The name of the user
              default: 'steve-harris'
    """
    return jsonify({'username': username})

app.register_blueprint(example_blueprint)

swag = Swagger(app)

if __name__ == "__main__":
    app.run(debug=True)
</code>```

Body:
I am adding Swagger UI to my Python Flask application using Flasgger. Most common examples on the Internet are for the basic Flask style using @app.route:

from flasgger.utils import swag_from

@app.route('/api/<string:username>')
@swag_from('path/to/external_file.yml')
def get(username):
    return jsonify({'username': username})

That works.

In my application however, I am not using @app.route decorators to define the endpoints. I am using flask Blueprints. Like following:

from flask import Flask, Blueprint
from flask_restful import Api, Resource
from flasgger.utils import swag_from
...

class TestResourceClass(Resource):

      @swag_from('docs_test_get.yml', endpoint='test')
      def get() :
         print "This is the get method for GET /1.0/myapi/test endpoint"

app = Flask(__name__)
my_api_blueprint = Blueprint('my_api', __name__)
my_api = Api(my_api_blueprint)

app.register_blueprint(my_api_blueprint, url_prefix='/1.0/myapi/')

my_api.add_resource(TestResourceClass, '/test/'
                        endpoint='test',
                        methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
....

As seen above, I used @swag_from decorator on the TestResourceClass.get() method which is bound to the GET method endpoint. I also have the endpoint=test  matching in the two places.

But I am not getting anything on the Swagger UI, it is all blank. The docs_test_get.yml file does contain the valid yaml markup to define the swagger spec.

What am I missing? How can I get Flasgger Swagger UI working with Flask Blueprint based setup?

Body:
Now there is an example of blueprint app in https://github.com/rochacbruno/flasgger/blob/master/examples/example_blueprint.py

"""
A test to ensure routes from Blueprints are swagged as expected.
"""
from flask import Blueprint, Flask, jsonify

from flasgger import Swagger
from flasgger.utils import swag_from

app = Flask(__name__)

example_blueprint = Blueprint("example_blueprint", __name__)

@example_blueprint.route('/usernames/<username>', methods=['GET', 'POST'])
@swag_from('username_specs.yml', methods=['GET'])
@swag_from('username_specs.yml', methods=['POST'])
def usernames(username):
    return jsonify({'username': username})

@example_blueprint.route('/usernames2/<username>', methods=['GET', 'POST'])
def usernames2(username):
    """
    This is the summary defined in yaml file
    First line is the summary
    All following lines until the hyphens is added to description
    the format of the first lines until 3 hyphens will be not yaml compliant
    but everything below the 3 hyphens should be.
    ---
    tags:
      - users
    parameters:
      - in: path
        name: username
        type: string
        required: true
    responses:
      200:
        description: A single user item
        schema:
          id: rec_username
          properties:
            username:
              type: string
              description: The name of the user
              default: 'steve-harris'
    """
    return jsonify({'username': username})

app.register_blueprint(example_blueprint)

swag = Swagger(app)

if __name__ == "__main__":
    app.run(debug=True)


问:
json data not working on server
I retreived my json data using Jquery ajax. My data is:

```<code>[{"id":"2","checkNo":"74152","routingNo":"896523","accountNo":"741236","confirmAccountNo":"85263","custEmail":"avn@gmail1.com","custName":"jonita gandhi","custStreetAddress":"address2","custPhone":"78456","custCity":"city2","custState":"state2","custZipCode":"4123","amount":"71","memo1":"memo3","memo2":"","cmp":"support","bankName":"Federal Bank","bankAddress":"A-19, Golden avenue","bankCity":"Florida","bankState":"FE","isDeleted":"0","createdDtm":"2017-05-30 14:47:48","updatedDtm":null}]
</code>```

On Jquery Success i hold the data in a variable

```<code>var jsonData = JSON.parse(JSON.stringify(data));
</code>```

when i am trying to access checkNo. using jsonData[0].checkNo it yields undefined but when i check it using

```<code>console.log(jsonData)
</code>```

It outputs data which is same as top.

Note: This problem yields only on server but it is working fine on my localhost.

Edit:

Here is my ajax call:

```<code>jQuery.ajax({
url: postUrl,
data:queryString,
type: "POST",
success:function(data){
    switch(action) {
      case "edit":
      jsonData = JSON.parse(data); console.log(jsonData);
      //var jsssss = JSON.parse(JSON.stringify(data)); console.log(jsssss);
      $("#custEmail").val(jsonData[0].custEmail);
      $("#custName").val(jsonData[0].custName);
      $("#custCheckNo").val(jsonData[0].checkNo);
      $("#edit_model").modal();
        break;
     //some more code
}
});
</code>```

答:
You don't need to parse and/or stringify your data. JQuery does this for you.</p>

```<code>$.ajax({
    type: "POST",
    contentType: "application/json",
    url: postUrl,
    data: queryString,
    dataType: "json",
    success:function(data){
        switch(action) {
          case "edit":
          jsonData = data;
          $("#custEmail").val(jsonData[0].custEmail);
    break;
    //some more code
  }
});
</code>```

Title: json data not working on server

Body:
I retreived my json data using Jquery ajax. My data is:

[{"id":"2","checkNo":"74152","routingNo":"896523","accountNo":"741236","confirmAccountNo":"85263","custEmail":"avn@gmail1.com","custName":"jonita gandhi","custStreetAddress":"address2","custPhone":"78456","custCity":"city2","custState":"state2","custZipCode":"4123","amount":"71","memo1":"memo3","memo2":"","cmp":"support","bankName":"Federal Bank","bankAddress":"A-19, Golden avenue","bankCity":"Florida","bankState":"FE","isDeleted":"0","createdDtm":"2017-05-30 14:47:48","updatedDtm":null}]

On Jquery Success i hold the data in a variable

var jsonData = JSON.parse(JSON.stringify(data));

when i am trying to access checkNo. using jsonData[0].checkNo it yields undefined but when i check it using

console.log(jsonData)

It outputs data which is same as top.

Note: This problem yields only on server but it is working fine on my localhost.

Edit:

Here is my ajax call:

jQuery.ajax({
url: postUrl,
data:queryString,
type: "POST",
success:function(data){
    switch(action) {
      case "edit":
      jsonData = JSON.parse(data); console.log(jsonData);
      //var jsssss = JSON.parse(JSON.stringify(data)); console.log(jsssss);
      $("#custEmail").val(jsonData[0].custEmail);
      $("#custName").val(jsonData[0].custName);
      $("#custCheckNo").val(jsonData[0].checkNo);
      $("#edit_model").modal();
        break;
     //some more code
}
});

Body:
You don't need to parse and/or stringify your data. JQuery does this for you.

$.ajax({
    type: "POST",
    contentType: "application/json",
    url: postUrl,
    data: queryString,
    dataType: "json",
    success:function(data){
        switch(action) {
          case "edit":
          jsonData = data;
          $("#custEmail").val(jsonData[0].custEmail);
    break;
    //some more code
  }
});

ContentLicense: CC BY-SA 4.0


问:
What is best practice to work with Liquibase across different application versions?
I would like to know how to handle versioning of application along with Liquibase files. Let's say that I have 4 application versions: 1.0, 2.0, 3.0, 4.0. In 4.0, I have the following structure :

```<code>> - 1.0-changeset.xml
> - 2.0-changeset.xml
> - 3.0-changeset.xml
> - 4.0-changeset.xml
> - changesetMaster.xml (include all above files)
</code>```

Respectively, version 3.0 of the application contains only 1.0, 2.0, 3.0 changeset files (without 4.0).

Now my question is: how do I handle bug fixing in different application versions, which require database changes?

For instance, a bug has been fixed in version 3.0. If the bug appears in 4.0 should I add changes to 3.0-changeset.xml in 3.0 application version, and 3.0-changeset.xml in 4.0 application version ? Or in 4.0 application version should I add it to 4.0-changeset.xml? The same question applies to the bug which exists only in 3.0 version. Should I add then a fix to 4.0 version too ?

Generally speaking, what is the best way to manage liquibase changeset files across different application versions?

答:
Your application source code is stored in a version control system (VCS) like git. For different releases you use different branches.

You have only one liquibase changelog file that contains all database changes from the beginning of time to the current development version. This changelog is stored in your VCS along with the application source code.

When you fix a bug in the current development branch and the versions 4.0 and 3.0, you make a commit on each of these branches that contains the code changes along with a new change set in the liquibase changelog.

During a build, you check out the software and the changelog from the desired branch and build the application. During deployment, you install the new application code and run a liquibase update against the database.

Body:
I would like to know how to handle versioning of application along with Liquibase files. Let's say that I have 4 application versions: 1.0, 2.0, 3.0, 4.0. In 4.0, I have the following structure :

> - 1.0-changeset.xml
> - 2.0-changeset.xml
> - 3.0-changeset.xml
> - 4.0-changeset.xml
> - changesetMaster.xml (include all above files)

Respectively, version 3.0 of the application contains only 1.0, 2.0, 3.0 changeset files (without 4.0).

Now my question is: how do I handle bug fixing in different application versions, which require database changes?

For instance, a bug has been fixed in version 3.0. If the bug appears in 4.0 should I add changes to 3.0-changeset.xml in 3.0 application version, and 3.0-changeset.xml in 4.0 application version ? Or in 4.0 application version should I add it to 4.0-changeset.xml? The same question applies to the bug which exists only in 3.0 version. Should I add then a fix to 4.0 version too ?

Generally speaking, what is the best way to manage liquibase changeset files across different application versions?


答:
Try with #riga_ristorante_1  p:hover just give toggle effect

#riga_ristorante_1  p:hover {
     text-align: center;
     color: blue;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="riga_ristorante_1" >
<div>
  <p>HI</p>
</div>
<div><p>HOME</p></div>
<div><p>DOG</p></div>
</div></code>```

Body:
Try with #riga_ristorante_1  p:hover just give toggle effect

#riga_ristorante_1  p:hover {
     text-align: center;
     color: blue;

}

<div id="riga_ristorante_1" >
<div>
  <p>HI</p>
</div>
<div><p>HOME</p></div>
<div><p>DOG</p></div>
</div>


问:
All about list in python3
My code is:

```<code>    a         = 3.5
    list      = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
    bigList   = []
    smallList = []
    for i in list:
        if a < i:
            bigList.append( i )
        else:
            smallList.append( i )
    print( min( bigList ) )
    print( max( smallList ) )
</code>```

My question: Is there a function or a smarter way to get the smaller value and the greater value than a ( example: if a = 6.1, a smaller value will be 6 and a greater value will be 7) without creating two new lists as I did?

Thank you so much.

答:
You can use bisect if the list is sorted:

```<code>import bisect
insertion_point = bisect.bisect_right(lst, a)
small = lst[max(insertion_point - 1, 0)]
big = lst[min(insertion_point, len(lst) - 1)]
</code>```

This will always return a value in small and big closest to the relative insertion point.

About bisect_right:

returns an insertion point which comes after (to the right of) any existing entries of item in list.

Note: you shouldn't shadow list which is part of python. Use lst or a similar name.

Title: All about list in python3

Body:
My code is:

    a         = 3.5
    list      = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
    bigList   = []
    smallList = []
    for i in list:
        if a < i:
            bigList.append( i )
        else:
            smallList.append( i )
    print( min( bigList ) )
    print( max( smallList ) )

My question: Is there a function or a smarter way to get the smaller value and the greater value than a ( example: if a = 6.1, a smaller value will be 6 and a greater value will be 7) without creating two new lists as I did?

Thank you so much.

Body:
You can use bisect if the list is sorted:

import bisect
insertion_point = bisect.bisect_right(lst, a)
small = lst[max(insertion_point - 1, 0)]
big = lst[min(insertion_point, len(lst) - 1)]

This will always return a value in small and big closest to the relative insertion point.

About bisect_right:

returns an insertion point which comes after (to the right of) any existing entries of item in list.

Note: you shouldn't shadow list which is part of python. Use lst or a similar name.


问:
How to create a tensorflow dataset from a CSV file in R to train a Multilayer perceptron
I have been working several times with tensorflow in Python. I always use keras because it has a very nice syntax.

Currently I have to implement a multilayer perceptron un R.

In the tutorial that appear in:
https://tensorflow.rstudio.com/tutorial_mnist_pros.html

They directly load the mnist dataset in their own format:

```<code>input_dataset <- tf$examples$tutorials$mnist$input_data
mnist <- input_dataset$read_data_sets("MNIST-data", one_hot = TRUE)
</code>```

And they use it using their functions to obtain the batches:

```<code>for (i in 1:1000) {
    batches <- mnist$train$next_batch(100L)
    batch_xs <- batches[[1]]
    batch_ys <- batches[[2]]
    sess$run(train_step,feed_dict = dict(x = batch_xs, y_ = batch_ys))
}
</code>```

I have my dataset in a csv file and I load it into a data frame, but I have absolutely no idea about how to transform it in a tensorflow dataset in order to use functions like next_batch.

Any tip to solve this problem?

Thank you very much in advance

答:
See class Dataset and some helper functions in base.py in TF.

Reference:

tensorflow/tensorflow/contrib/learn/python/learn/datasets/base.py

tensorflow/tensorflow/contrib/learn/python/learn/datasets/mnist.py

Body:
I have been working several times with tensorflow in Python. I always use keras because it has a very nice syntax.

Currently I have to implement a multilayer perceptron un R.

In the tutorial that appear in:
https://tensorflow.rstudio.com/tutorial_mnist_pros.html

They directly load the mnist dataset in their own format:

input_dataset <- tf$examples$tutorials$mnist$input_data
mnist <- input_dataset$read_data_sets("MNIST-data", one_hot = TRUE)

And they use it using their functions to obtain the batches:

for (i in 1:1000) {
    batches <- mnist$train$next_batch(100L)
    batch_xs <- batches[[1]]
    batch_ys <- batches[[2]]
    sess$run(train_step,feed_dict = dict(x = batch_xs, y_ = batch_ys))
}

I have my dataset in a csv file and I load it into a data frame, but I have absolutely no idea about how to transform it in a tensorflow dataset in order to use functions like next_batch.

Any tip to solve this problem?

Thank you very much in advance


问:
QT client doesn't download file when action is placed on button
Code in main.cpp

```<code>Client c;
c.start("ip-address", port, "final folder/file");
</code>```

It works and client downloads file I need.

But if I place same code in mainwindow.cpp on button click action

```<code>void MainWindow::on_btn_connect_clicked()
{
    Client c;
    c.start("ip-address", port, "final folder/file");
}
</code>```

it doesn't work. Why is that? I'm newbie at Qt and network coding. Some source code

```<code>void Client::start(QString address, qint16 port, QString file)
{
    qDebug() << "client started";
    QHostAddress addr(address);
    filename = file;
    client->connectToHost(addr, port);
    qDebug() << client->socketDescriptor();
}
</code>```

I have readyRead() but programm doesn't get there.

```<code>Client::Client(QObject *parent) :
    QObject(parent)
{
    client = new QTcpSocket(this);
    client->abort();
    connect(client, SIGNAL(readyRead()), this, SLOT(ReadData()));
    connect(client, SIGNAL(disconnected()), this, SLOT(Completed()));
}
</code>```

答:
When you create the Client like this:

```<code>void MainWindow::on_btn_connect_clicked()
{
    Client c;
    c.start("ip-address", port, "final folder/file");
}
</code>```

The client object is created, start is called, then it is immediately destroyed one execution leaves the on_btn_conenct_clicked() function. This will never work unless the "start" function is completely finished doing whatever you want it to do by the time you leave it, which does not appear to be the case by the code you posted.

For this to work, you'd have to make client a member of the MainWindow class so it sticks around after the slot is called. Another alternative would be to make it a pointer, create it in the on_btn_connect_clicked() slot, then connect whatever signal gets emitted when its all done with its work to its own deleteLater slot. Like so:

```<code>void MainWindow::on_btn_connect_clicked()
{
    Client* c = new Client(this);
    connect(c, &Client::downloadComplete, c, &Client::deleteLater);
    c->start("ip-address", port, "final folder/file");
}
</code>```

The downloadComplete signal is something that you have to make sure you emit yourself whenever the action you are trying to accomplish is completed, otherwise you'll have a memory leak and the client object will not get deleted until the entire MainWindow is deleted.

Body:
Code in main.cpp

Client c;
c.start("ip-address", port, "final folder/file");

It works and client downloads file I need.

But if I place same code in mainwindow.cpp on button click action

void MainWindow::on_btn_connect_clicked()
{
    Client c;
    c.start("ip-address", port, "final folder/file");
}

it doesn't work. Why is that? I'm newbie at Qt and network coding. Some source code

void Client::start(QString address, qint16 port, QString file)
{
    qDebug() << "client started";
    QHostAddress addr(address);
    filename = file;
    client->connectToHost(addr, port);
    qDebug() << client->socketDescriptor();
}

I have readyRead() but programm doesn't get there.

Client::Client(QObject *parent) :
    QObject(parent)
{
    client = new QTcpSocket(this);
    client->abort();
    connect(client, SIGNAL(readyRead()), this, SLOT(ReadData()));
    connect(client, SIGNAL(disconnected()), this, SLOT(Completed()));
}

Body:
When you create the Client like this:

void MainWindow::on_btn_connect_clicked()
{
    Client c;
    c.start("ip-address", port, "final folder/file");
}

The client object is created, start is called, then it is immediately destroyed one execution leaves the on_btn_conenct_clicked() function. This will never work unless the "start" function is completely finished doing whatever you want it to do by the time you leave it, which does not appear to be the case by the code you posted.

For this to work, you'd have to make client a member of the MainWindow class so it sticks around after the slot is called. Another alternative would be to make it a pointer, create it in the on_btn_connect_clicked() slot, then connect whatever signal gets emitted when its all done with its work to its own deleteLater slot. Like so:

void MainWindow::on_btn_connect_clicked()
{
    Client* c = new Client(this);
    connect(c, &Client::downloadComplete, c, &Client::deleteLater);
    c->start("ip-address", port, "final folder/file");
}

The downloadComplete signal is something that you have to make sure you emit yourself whenever the action you are trying to accomplish is completed, otherwise you'll have a memory leak and the client object will not get deleted until the entire MainWindow is deleted.


问:
Mulesoft HTTP Connector configuration
When I connect to:

```<code>http://legacy.cafebonappetit.com/api/2/menus?cafe=261
</code>```

I get back JSON as I should. However, I'm unable to do this with the Mulesoft HTTP Connector. When I try, I get back 500.  Here is my XML:

```<code>    <flow name="GetDiningInfo">
    <http:listener config-ref="HTTP_Listener_Configuration" path="/dining" doc:name="HTTP"/>
    <http:request config-ref="HTTP_Request_Configuration" path="/api/2/menus" method="GET" doc:name="GET announcement from dining server" followRedirects="true" host="legacy.cafebonappetit.com" port="80">
        <http:request-builder>
            <http:query-param paramName="cafe" value="261"/>
        </http:request-builder>
    </http:request>
    <logger level="INFO" doc:name="Logger"/>
</flow>
</code>```

The connector global config is:

```<code>    <http:request-config name="HTTPReqConfigforCafeBonAppetit.com" host="legacy.cafebonappetit.com" port="80" basePath="/api/2" doc:name="HTTP Request Configuration"/>
</code>```

What am I doing wrong?

Thanks...

UPDATE: Still no joy. I'm still getting back a 500 internal server failure through Mule.

Here is the latest code that does not duplicate the path:

```<code><http:request-config name="HTTPReqConfigforCafeBonAppetit" host="legacy.cafebonappetit.com" port="80" basePath="/api/2/" doc:name="HTTP Request Configuration" usePersistentConnections="false"/>

<flow name="GetDiningInfo">
    <http:listener config-ref="HTTP_Listener_Configuration" path="/dining" doc:name="HTTP"/>
    <http:request config-ref="HTTPReqConfigforCafeBonAppetit" path="menus" method="GET" doc:name="GET menu" followRedirects="true" parseResponse="false">
        <http:request-builder>
            <http:query-param paramName="cafe" value="261"/>
        </http:request-builder>
    </http:request>
    <logger level="INFO" doc:name="Logger"/>
</flow>
</code>```

答:
The server for legacy.cafebonappetit.com cannot handle the header Host including the port (which is valid).
The HTTP connector sends Host: legacy.cafebonappetit.com:80 by default causing the server to reject the request, so you need to explicitly add the Host header, as in the example below.
enter image description here</p>

Title: Mulesoft HTTP Connector configuration

Body:
When I connect to:

http://legacy.cafebonappetit.com/api/2/menus?cafe=261

I get back JSON as I should. However, I'm unable to do this with the Mulesoft HTTP Connector. When I try, I get back 500.  Here is my XML:

    <flow name="GetDiningInfo">
    <http:listener config-ref="HTTP_Listener_Configuration" path="/dining" doc:name="HTTP"/>
    <http:request config-ref="HTTP_Request_Configuration" path="/api/2/menus" method="GET" doc:name="GET announcement from dining server" followRedirects="true" host="legacy.cafebonappetit.com" port="80">
        <http:request-builder>
            <http:query-param paramName="cafe" value="261"/>
        </http:request-builder>
    </http:request>
    <logger level="INFO" doc:name="Logger"/>
</flow>

The connector global config is:

    <http:request-config name="HTTPReqConfigforCafeBonAppetit.com" host="legacy.cafebonappetit.com" port="80" basePath="/api/2" doc:name="HTTP Request Configuration"/>

What am I doing wrong?

Thanks...

UPDATE: Still no joy. I'm still getting back a 500 internal server failure through Mule.

Here is the latest code that does not duplicate the path:

<http:request-config name="HTTPReqConfigforCafeBonAppetit" host="legacy.cafebonappetit.com" port="80" basePath="/api/2/" doc:name="HTTP Request Configuration" usePersistentConnections="false"/>

<flow name="GetDiningInfo">
    <http:listener config-ref="HTTP_Listener_Configuration" path="/dining" doc:name="HTTP"/>
    <http:request config-ref="HTTPReqConfigforCafeBonAppetit" path="menus" method="GET" doc:name="GET menu" followRedirects="true" parseResponse="false">
        <http:request-builder>
            <http:query-param paramName="cafe" value="261"/>
        </http:request-builder>
    </http:request>
    <logger level="INFO" doc:name="Logger"/>
</flow>


问:
Runtime Error: Method or data member not found
I receive the error: Method or data member not found at line

.SendKeys ("")

I am scraping from a screen and this the command I send to place the cursor in the right place before sending the command in the next line to change screens. I do not understand why I am receiving this error.

```<code>Sub RLinfo()

    Dim sys
    Dim sess
    Dim chan
    Dim ws As Worksheet
    Dim x As Integer
    Dim y As Integer
    Dim linecount As Long
    ' RL Information xxxx

    Set Host = CreateObject("BZWh.WhllObj")
    Host.OpenSession 0, 1, "xxxx.zmd", 30, 1
    Set sess = Host.ActiveSession
    Set chan = sess.Screen
    Set ws = Worksheets("Information")
    With ws
    x = 14
    y = 19

    Set OUTPUTSHEET = ActiveWorkbook.Sheets("Information")

    With chan

    linecount = 2
        Do While OUTPUTSHEET.Cells(linecount, 30) = "Zip"
            RL = Format(OUTPUTSHEET.Cells(linecount, 1), "000000000")

            .SendKeys ("<Home>")
            .SendKeys ("/for x203<Enter>")
            .waithostquiet (10)
            .SendKeys (RL & "<Enter>")
            .waithostquiet (10)
        If Trim(.getstring(14, 2, 30)) = "RL WAS NOT FOUND" Then
            OUTPUTSHEET.Cells(linecount, 20) = "RL No Longer In X203"
            GoTo Found
        Else
        End If
            OUTPUTSHEET.Cells(linecount, 17) = Trim(.getstring(11, 6, 6))
            OUTPUTSHEET.Cells(linecount, 18) = Trim(.getstring(8, 27, 12))
            OUTPUTSHEET.Cells(linecount, 19) = Trim(.getstring(9, 27, 12))
            OUTPUTSHEET.Cells(linecount, 20) = Trim(.getstring(5, 41, 26))

        For x = 14 To 20
            If Trim(.getstring(x, 2, 7)) = "NUM" Then
           OUTPUTSHEET.Cells(linecount, 21) = Trim(.getstring(x, 11, 11))
           GoTo Found
           Else
            End If
        Next x

         If Trim(.getstring(23, 72, 6)) = "N MORE" Then
         .SendKeys ("<PA1>")
         .waithostquiet (10)
         For y = 19 To 22
            If Trim(.getstring(y, 2, 7)) = "NUM" Then
           OUTPUTSHEET.Cells(linecount, 21) = Trim(.getstring(y, 11, 11))
           GoTo Found
           Else
            End If
        Next y
        Else
        End If
    Found:
            linecount = linecount + 1
       Loop
        End With
        End With
    ws.Cells(2, 31) = linecount
    endM:
End Sub
</code>```

答: The cause of my problem was that I was not disconnecting from the Host when I moved between modules. At the start of each module I was reconnecting to the Host even though I had not disconnected in the previous module and this caused the run time error.</p>

Body:
I receive the error: Method or data member not found at line

.SendKeys ("")

I am scraping from a screen and this the command I send to place the cursor in the right place before sending the command in the next line to change screens. I do not understand why I am receiving this error.

Sub RLinfo()

    Dim sys
    Dim sess
    Dim chan
    Dim ws As Worksheet
    Dim x As Integer
    Dim y As Integer
    Dim linecount As Long
    ' RL Information xxxx

    Set Host = CreateObject("BZWh.WhllObj")
    Host.OpenSession 0, 1, "xxxx.zmd", 30, 1
    Set sess = Host.ActiveSession
    Set chan = sess.Screen
    Set ws = Worksheets("Information")
    With ws
    x = 14
    y = 19

    Set OUTPUTSHEET = ActiveWorkbook.Sheets("Information")

    With chan

    linecount = 2
        Do While OUTPUTSHEET.Cells(linecount, 30) = "Zip"
            RL = Format(OUTPUTSHEET.Cells(linecount, 1), "000000000")

            .SendKeys ("<Home>")
            .SendKeys ("/for x203<Enter>")
            .waithostquiet (10)
            .SendKeys (RL & "<Enter>")
            .waithostquiet (10)
        If Trim(.getstring(14, 2, 30)) = "RL WAS NOT FOUND" Then
            OUTPUTSHEET.Cells(linecount, 20) = "RL No Longer In X203"
            GoTo Found
        Else
        End If
            OUTPUTSHEET.Cells(linecount, 17) = Trim(.getstring(11, 6, 6))
            OUTPUTSHEET.Cells(linecount, 18) = Trim(.getstring(8, 27, 12))
            OUTPUTSHEET.Cells(linecount, 19) = Trim(.getstring(9, 27, 12))
            OUTPUTSHEET.Cells(linecount, 20) = Trim(.getstring(5, 41, 26))

        For x = 14 To 20
            If Trim(.getstring(x, 2, 7)) = "NUM" Then
           OUTPUTSHEET.Cells(linecount, 21) = Trim(.getstring(x, 11, 11))
           GoTo Found
           Else
            End If
        Next x

         If Trim(.getstring(23, 72, 6)) = "N MORE" Then
         .SendKeys ("<PA1>")
         .waithostquiet (10)
         For y = 19 To 22
            If Trim(.getstring(y, 2, 7)) = "NUM" Then
           OUTPUTSHEET.Cells(linecount, 21) = Trim(.getstring(y, 11, 11))
           GoTo Found
           Else
            End If
        Next y
        Else
        End If
    Found:
            linecount = linecount + 1
       Loop
        End With
        End With
    ws.Cells(2, 31) = linecount
    endM:
End Sub


问:
retrofit 2 post rxjava (login)
I'm new using retrofit2 and rxjava, i was able to use GET to get information from api's but now, using POST for a login request is not working how is suposed too.

```<code>Application application = Application.get(mLoginView.getContext());
        Service Service = application.getmService();
        Log.i(TAG,""+username);
        Log.i(TAG,""+password);
        mSubscription = Service.login(username,password)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<User>() {

                    @Override
                    public void onCompleted() {
                        Log.i(TAG,"User: " + mUser.getHash());
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        Log.i(TAG,"USERNAME DON'T EXIST");
                    }

                    @Override
                    public void onNext(User user) {

                       // LoginPresenter.this.mUser = user;
                    }
                });
</code>```

Service:

```<code>public interface Service {

String mUrl = "https://blabla.com/api/index.php/";  // TODO Change

@FormUrlEncoded
@POST("user/login")
Observable<User> login(@Field(value="email",encoded=true)  String email, @Field(value="password",encoded = true) String password );
</code>```

I enter a POST with username and pass from an existing user and return me a 404 page and not the hash im supposed to get.

Thank you

答:
I forgot this was here, I found a solutions months ago, and what i did was create a object UserCredentials to do the body request and a object to get the response.</p>

```<code>@POST("user/login")
Observable<LoginResponse> login(@Body UserCredentials userCredentials);
</code>```

Title: retrofit 2 post rxjava (login)

Body:
I'm new using retrofit2 and rxjava, i was able to use GET to get information from api's but now, using POST for a login request is not working how is suposed too.

Application application = Application.get(mLoginView.getContext());
        Service Service = application.getmService();
        Log.i(TAG,""+username);
        Log.i(TAG,""+password);
        mSubscription = Service.login(username,password)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<User>() {

                    @Override
                    public void onCompleted() {
                        Log.i(TAG,"User: " + mUser.getHash());
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        Log.i(TAG,"USERNAME DON'T EXIST");
                    }

                    @Override
                    public void onNext(User user) {

                       // LoginPresenter.this.mUser = user;
                    }
                });

Service:

public interface Service {

String mUrl = "https://blabla.com/api/index.php/";  // TODO Change

@FormUrlEncoded
@POST("user/login")
Observable<User> login(@Field(value="email",encoded=true)  String email, @Field(value="password",encoded = true) String password );

I enter a POST with username and pass from an existing user and return me a 404 page and not the hash im supposed to get.

Thank you

Body:
I forgot this was here, I found a solutions months ago, and what i did was create a object UserCredentials to do the body request and a object to get the response.

@POST("user/login")
Observable<LoginResponse> login(@Body UserCredentials userCredentials);


问:
GCode and RS232
I am attempting to read a RS232/USB input from a Gcode script. Is it possible to perform this from GCode or am I going to have to wrap it in python or something?

For reference, my algorithm is essentially:

-Perform some CNC movements

-Read/store/record variable from RS232 peripheral

-Repeat a bunch of times in marginally different ways

答: Gcode per se doesn't support reading anything from any peripheral.  Gcode is nothing more than a line-oriented textual machine command format, and is typically fed from a storage medium or file into an interpreter.  This interpreter determines the axes movements, usually incorporating some trajectory planner.  Then the interpreter emits signals to a peripheral device (LPT port, special card, etc.) that are fed to motor controllers.  So without more details, based on your question, I think you're going to need something else to handle any serial connection.  If you could clarify or add more details a solution may become apparent.

Title: GCode and RS232


问:
MKMapView set style to black and white
i'm trying to change the color scheme of the MKMapView to black and white. It's discussed in this topic: Black and white overlay for an MKMapView but i have no clue how to achieve this.

Can somebody help me out?

Best regards,
Lukas

答:
The solution is pretty straightforward. By using the GoogleMaps SDK you can set a mapstyle.

One can create styles through the following two sites:
https://snazzymaps.com
https://mapstyle.withgoogle.com

Btw: I noticed the GoogleMaps SDK is faster, more developer friendly, and offers more features anyway, so I'd recommend it anyway.

Title: MKMapView set style to black and white


问:
How to do IP walk in C
my computer's IP is 192.168.1.101 over eth0.

I want to know what are other active/used IP under 192.168.1.*

I am expecting a list of IP address that is ping-able under 192.168.1.*

How can I do that in C? And preferably in linux platform.

Any C functions available?

答:
There is no built-in function in C that sends ping packet. There is, however, function that just sends packet. There is also a lot of code in the internet that already implements ping.

What you have to do is just take one of them (this for example) and ping in a loop for all addresses in your network.

You should know, however, that ping is not a reliable way of saying which addresses are in use. RFC 792 - Internet Control Message Protocol says:

The Internet Protocol is not designed
  to be absolutely reliable. The purpose
  of these control messages is to
  provide feedback about problems in the
  communication environment, not to make
  IP reliable. There are still no guarantees that a datagram will be
  delivered or a    control message will
  be returned.  Some datagrams may still
  be    undelivered without any report
  of their loss.

which means that any message can be easily lost, with no notification. Furthermore, target does not have to respond.

Title: How to do IP walk in C


问:
How to declare an array with size modification in a subroutine?
I did a subroutine MatPath to append an array but I don't understand how I should declare this array in the subroutine where I call MatPath :

```<code>!**********************************************************************
SUBROUTINE MatPath(Path, Start)
INTEGER(2),PARAMETER::Ximax = 5, Yimax = 5, Zimax = 1
INTEGER(4)::W,B
REAL(8), DIMENSION(:,:), ALLOCATABLE::Path
REAL(8), DIMENSION(:,:), ALLOCATABLE::Temp_Array
REAL(8), DIMENSION(:), ALLOCATABLE::Start
W=SIZE(Path,DIM=2)
ALLOCATE(Temp_Array(3,W))
DEALLOCATE(Path)
ALLOCATE(Path(3,W+1))
Path(:,1:W)=Temp_Array(:,1:W)
Path(:,W+1)=Start(:)
DEALLOCATE(Temp_Array)

RETURN
END SUBROUTINE MatPath
!************************************************
SUBROUTINE FINDPATH(Array, St)
IMPLICIT NONE
INTEGER(4), DIMENSION(3,3)::Array
REAL(8), DIMENSION(3)::St
REAL(8), DIMENSION(3, :)::Path !PROBLEM HERE

CALL MatPath(Path, St)

END SUBROUTINE FINDPATH
</code>```

It's still unclear how I can declare an array which the size would be modify in a subroutine ... If someone can explain how it work, Thanks !

EDIT

To be more clear here a simplification of my problem how can I get modification of the size of my array A and pass it between the main program end the subroutine ? :

```<code>program teste10

REAL(8),DIMENSION(:,:),ALLOCATABLE::A

ALLOCATE(A(2,2))
A=1
WRITE(*,*), "Initial A : ", A

CALL TESTE1(A)

WRITE(*,*) "new A : ", A

DEALLOCATE(A)
STOP
end program teste10
!**********************************************
SUBROUTINE TESTE1(A)

REAL(8),DIMENSION(:,:),INTENT(INOUT), ALLOCATABLE::A
REAL(8), DIMENSION(:,:), ALLOCATABLE::Temp
INTEGER(4)::X, Y

X=SIZE(A, DIM=1)
Y=SIZE(A, DIM=2)
ALLOCATE(Temp(X,Y))
DEALLOCATE(A)
ALLOCATE(A(X+2,Y+3))
A(1:X, 1:Y)=Temp(1:X,1:Y)
A(X+1:X+2, Y+1:Y+3)=0
DEALLOCATE(Temp)

RETURN
END SUBROUTINE TESTE1
</code>```

When I try to do that it give me a "SIGSEV, segmentation fault occured" or just run forever without any message....

答:
First, there was certainly some error message from the compiler. Please show your error messages in our questions.

In the called subroutine, you declare the dummy arguments allocatable. That is correct.

In the calling subroutine, you didn't declared the arrays allocatable. That is not correct. If you pass any variable into an allocatable dummy argument, the variable must itself be allocatable.

So both Path and St have to be allocatable inside FINDPATH.

You probably can remove the allocatable attribute from Start and then St will not have to be allocatable either.

So (not tested):

```<code>!**********************************************************************
SUBROUTINE MatPath(Path, Start)
  INTEGER  ::  W
  REAL(something_better), DIMENSION(:,:), ALLOCATABLE :: Path
  REAL(something_better), DIMENSION(:,:), ALLOCATABLE :: Temp_Array
  REAL(something_better), DIMENSION(:),               :: Start

  W=SIZE(Path,DIM=2)
  ALLOCATE(Temp_Array(3,W))
  DEALLOCATE(Path)
  ALLOCATE(Path(3,W+1))
  Path(:,1:W)=Temp_Array(:,1:W)
  Path(:,W+1)=Start(:)
  DEALLOCATE(Temp_Array)
END SUBROUTINE MatPath
!************************************************

SUBROUTINE FINDPATH(Array, St)
  INTEGER, DIMENSION(3,3) :: Array
  REAL(something_better), DIMENSION(3) :: St
  REAL(something_better), DIMENSION(3, :), allocatable :: Path

  CALL MatPath(Path, St)

  !here do something with Path and Array?
  !it is not clear what does Path and what does Array
END SUBROUTINE FINDPATH
</code>```

Moreover, the presence of IMPLICIT NONE in the calling subroutine is leading me to suspicion that your subroutines are not in a module. They have to be in a module or the explicit interface must be established by some other means because allocatable arguments require explicit interface.

The second version (also not tested):

```<code>module Subroutines
  implicit none
  integer, parameter :: dp = kind(1.d0)

contains

    SUBROUTINE TESTE1(A)
      REAL(dp), DIMENSION(:,:), INTENT(INOUT), ALLOCATABLE :: A
      REAL(dp), DIMENSION(:,:), ALLOCATABLE :: Temp
      INTEGER :: X, Y

      X=SIZE(A, DIM=1)
      Y=SIZE(A, DIM=2)
      ALLOCATE(Temp(X,Y))
      DEALLOCATE(A)
      ALLOCATE(A(X+2,Y+3))
      A(1:X, 1:Y) = Temp(1:X,1:Y)
      A(X+1:X+2, Y+1:Y+3) = 0
      DEALLOCATE(Temp)
    END SUBROUTINE TESTE1

end module

program teste10
  use Subroutines

  implicit none

  REAL(dp), DIMENSION(:,:), ALLOCATABLE :: A

  ALLOCATE(A(2,2))
  A=1
  WRITE(*,*), "Initial A : ", A

  CALL TESTE1(A)

  WRITE(*,*) "new A : ", A

  DEALLOCATE(A)
end program teste10
</code>```

Here insert my usual rant about ugliness and non-portability of integer(4) and real(8).

I can't imagine why you  might want

```<code>INTEGER(2),PARAMETER::Ximax = 5, Yimax = 5, Zimax = 1
</code>```

instead of just

```<code>INTEGER, PARAMETER :: Ximax = 5, Yimax = 5, Zimax = 1
</code>```

There is simply no reason why the former might be better unless you pass it as an argument somewhere where kind 2 is required.

Body:
I did a subroutine MatPath to append an array but I don't understand how I should declare this array in the subroutine where I call MatPath :

!**********************************************************************
SUBROUTINE MatPath(Path, Start)
INTEGER(2),PARAMETER::Ximax = 5, Yimax = 5, Zimax = 1
INTEGER(4)::W,B
REAL(8), DIMENSION(:,:), ALLOCATABLE::Path
REAL(8), DIMENSION(:,:), ALLOCATABLE::Temp_Array
REAL(8), DIMENSION(:), ALLOCATABLE::Start
W=SIZE(Path,DIM=2)
ALLOCATE(Temp_Array(3,W))
DEALLOCATE(Path)
ALLOCATE(Path(3,W+1))
Path(:,1:W)=Temp_Array(:,1:W)
Path(:,W+1)=Start(:)
DEALLOCATE(Temp_Array)

RETURN
END SUBROUTINE MatPath
!************************************************
SUBROUTINE FINDPATH(Array, St)
IMPLICIT NONE
INTEGER(4), DIMENSION(3,3)::Array
REAL(8), DIMENSION(3)::St
REAL(8), DIMENSION(3, :)::Path !PROBLEM HERE

CALL MatPath(Path, St)

END SUBROUTINE FINDPATH

It's still unclear how I can declare an array which the size would be modify in a subroutine ... If someone can explain how it work, Thanks !

EDIT

To be more clear here a simplification of my problem how can I get modification of the size of my array A and pass it between the main program end the subroutine ? :

program teste10

REAL(8),DIMENSION(:,:),ALLOCATABLE::A

ALLOCATE(A(2,2))
A=1
WRITE(*,*), "Initial A : ", A

CALL TESTE1(A)

WRITE(*,*) "new A : ", A

DEALLOCATE(A)
STOP
end program teste10
!**********************************************
SUBROUTINE TESTE1(A)

REAL(8),DIMENSION(:,:),INTENT(INOUT), ALLOCATABLE::A
REAL(8), DIMENSION(:,:), ALLOCATABLE::Temp
INTEGER(4)::X, Y

X=SIZE(A, DIM=1)
Y=SIZE(A, DIM=2)
ALLOCATE(Temp(X,Y))
DEALLOCATE(A)
ALLOCATE(A(X+2,Y+3))
A(1:X, 1:Y)=Temp(1:X,1:Y)
A(X+1:X+2, Y+1:Y+3)=0
DEALLOCATE(Temp)

RETURN
END SUBROUTINE TESTE1

When I try to do that it give me a "SIGSEV, segmentation fault occured" or just run forever without any message....

Body:
First, there was certainly some error message from the compiler. Please show your error messages in our questions.

In the called subroutine, you declare the dummy arguments allocatable. That is correct.

In the calling subroutine, you didn't declared the arrays allocatable. That is not correct. If you pass any variable into an allocatable dummy argument, the variable must itself be allocatable.

So both Path and St have to be allocatable inside FINDPATH.

You probably can remove the allocatable attribute from Start and then St will not have to be allocatable either.

So (not tested):

!**********************************************************************
SUBROUTINE MatPath(Path, Start)
  INTEGER  ::  W
  REAL(something_better), DIMENSION(:,:), ALLOCATABLE :: Path
  REAL(something_better), DIMENSION(:,:), ALLOCATABLE :: Temp_Array
  REAL(something_better), DIMENSION(:),               :: Start

  W=SIZE(Path,DIM=2)
  ALLOCATE(Temp_Array(3,W))
  DEALLOCATE(Path)
  ALLOCATE(Path(3,W+1))
  Path(:,1:W)=Temp_Array(:,1:W)
  Path(:,W+1)=Start(:)
  DEALLOCATE(Temp_Array)
END SUBROUTINE MatPath
!************************************************

SUBROUTINE FINDPATH(Array, St)
  INTEGER, DIMENSION(3,3) :: Array
  REAL(something_better), DIMENSION(3) :: St
  REAL(something_better), DIMENSION(3, :), allocatable :: Path

  CALL MatPath(Path, St)

  !here do something with Path and Array?
  !it is not clear what does Path and what does Array
END SUBROUTINE FINDPATH

Moreover, the presence of IMPLICIT NONE in the calling subroutine is leading me to suspicion that your subroutines are not in a module. They have to be in a module or the explicit interface must be established by some other means because allocatable arguments require explicit interface.

The second version (also not tested):

module Subroutines
  implicit none
  integer, parameter :: dp = kind(1.d0)

contains

    SUBROUTINE TESTE1(A)
      REAL(dp), DIMENSION(:,:), INTENT(INOUT), ALLOCATABLE :: A
      REAL(dp), DIMENSION(:,:), ALLOCATABLE :: Temp
      INTEGER :: X, Y

      X=SIZE(A, DIM=1)
      Y=SIZE(A, DIM=2)
      ALLOCATE(Temp(X,Y))
      DEALLOCATE(A)
      ALLOCATE(A(X+2,Y+3))
      A(1:X, 1:Y) = Temp(1:X,1:Y)
      A(X+1:X+2, Y+1:Y+3) = 0
      DEALLOCATE(Temp)
    END SUBROUTINE TESTE1

end module

program teste10
  use Subroutines

  implicit none

  REAL(dp), DIMENSION(:,:), ALLOCATABLE :: A

  ALLOCATE(A(2,2))
  A=1
  WRITE(*,*), "Initial A : ", A

  CALL TESTE1(A)

  WRITE(*,*) "new A : ", A

  DEALLOCATE(A)
end program teste10

Here insert my usual rant about ugliness and non-portability of integer(4) and real(8).

I can't imagine why you  might want

INTEGER(2),PARAMETER::Ximax = 5, Yimax = 5, Zimax = 1

instead of just

INTEGER, PARAMETER :: Ximax = 5, Yimax = 5, Zimax = 1

There is simply no reason why the former might be better unless you pass it as an argument somewhere where kind 2 is required.


问:
Remove Left Margin of Microsoft Chart Control
How to remove the left margin of a Microsoft Chart Control (Shown as a red rectangle)?

The chart control is docked in the parent form. It seems that this margin is dynamic and depends on the chart width.

I cannot find such an option. Do I need to work with ChartArea location?

This is a .NET C#, WinForms application.

答:
If you want to remove all the paddings:</p>

```<code>Chart1.ChartAreas[0].Position.X = 0;

Chart1.ChartAreas[0].Position.Width = 100;

Chart1.ChartAreas[0].Position.Height = 100;

Chart1.ChartAreas[0].Position.Y = 0;
</code>```

Body:
If you want to remove all the paddings:

Chart1.ChartAreas[0].Position.X = 0;

Chart1.ChartAreas[0].Position.Width = 100;

Chart1.ChartAreas[0].Position.Height = 100;

Chart1.ChartAreas[0].Position.Y = 0;


问:
Blending semi-transparent bitmaps containing text with Graphics32
I'm trying to implement a layered painting system inside one of our internal components and I have problems blending bitmaps containing text.

Following code fragment shows the problem:

```<code>uses
  GR32;

procedure DrawBitmaps;
var
  bmp1: TBitmap32;
  bmp2: TBitmap32;
begin
  bmp1 := TBitmap32.Create;
  bmp1.Width := 100;
  bmp1.Height := 100;
  bmp1.FillRect(0, 0, 100, 100, clWhite32);
  bmp1.FillRect(0, 0, 80, 80, clTrGreen32);

  bmp1.Font.Size := -16;
  bmp1.Font.Color := clBlack;
  bmp1.TextOut(2, 10, 'Green');

  bmp1.SaveToFile('c:\0\bmp1.bmp');

  bmp2 := TBitmap32.Create;
  bmp2.Width := 80;
  bmp2.Height := 80;
  bmp2.FillRect(0, 0, 80, 80, clTrRed32);

  bmp2.Font.Size := -16;
  bmp2.Font.Color := clBlack;
  bmp2.TextOut(2, 50, 'Red');

  bmp2.SaveToFile('c:\0\bmp2.bmp');

  bmp2.DrawMode := dmBlend;
  bmp2.DrawTo(bmp1, 20, 20);

  bmp1.SaveToFile('c:\0\bmpcombined.bmp');

  bmp1.Free;
  bmp2.Free;
end;
</code>```

Resulting images:

bmp1:
bmp2:
bmpcombined:

As you can see, text is painted in black on bmp and bmp2, but appears white on bmpcombined.

I'm guessing the problem lies in TextOut which maps to Windows.ExtTextOut (via GR32_Backends_VCL.pas, TGDIBackend.Textout). That method doesn't handle transparency and paints text with alpha 00 (color is $000000 instead of $FF000000).

As a quick fix, setting bmp2.Font.Color to $FF000000 doesn't help.

```<code>bmp2.Font.Color := TColor(clBlack32);
</code>```

I am using fresh sources from GitHub

How should I paint a non-transparent text on a semi-transparent background so that I could blend this into a larger picture?

答:
The best solution I could find requires three helper functions.

TransparentToOpaque changes all fully transparent pixels to opaque.

```<code>procedure TransparentToOpaque(bmp: TCustomBitmap32);
var
  I: Integer;
  D: PColor32Entry;
begin
  D := PColor32Entry(@bmp.Bits[0]);
  for I := 0 to bmp.Width * bmp.Height - 1 do begin
    if D.A = 0 then
      D.A := $FF;
    Inc(D);
  end;
  bmp.Changed;
end;
</code>```

FlipTransparency changes all fully transparent pixels to opaque and vice versa.

```<code>procedure FlipTransparency(bmp: TCustomBitmap32);
var
  I: Integer;
  D: PColor32Entry;
begin
  D := PColor32Entry(@bmp.Bits[0]);
  for I := 0 to bmp.Width * bmp.Height - 1 do begin
    if D.A = 0 then
      D.A := $FF
    else if D.A = $FF then
      D.A := 0;
    Inc(D);
  end;
  bmp.Changed;
end;
</code>```

MakeOpaque marks all pixels as opaque.

```<code>procedure MakeOpaque(bmp: TCustomBitmap32);
var
  I: Integer;
  D: PColor32Entry;
begin
  D := PColor32Entry(@bmp.Bits[0]);
  for I := 0 to bmp.Width * bmp.Height - 1 do begin
    D.A := $FF;
    Inc(D);
  end;
  bmp.Changed;
end;
</code>```

Following tricks can then be applied.

After drawing text on the main image bmp1 which doesn't contain transparent pixels, code calls TransparentToOpaque to prevent problems with blending later on.

When drawing on a (semi)transparent bitmap bmp2, code creates yet another bitmap bmp3 and fills it with an opaque version of that (semi)transparent bitmap. This will ensure that font is aliased to correct colors in the TextOut call.

After the TextOut bmp3 contains opaque background and transparent text. FlipTransparency is then called to generate opaque text on a transparent background.

bmp3 is blended onto bmp2. This gives up opaque text on a (semi)transparent background.

bmp2 is blended onto bmp1.

Example code:

```<code>procedure TForm53.DrawBitmaps;
var
  bmp1: TBitmap32;
  bmp2: TBitmap32;
  bmp3: TBitmap32;
begin
  bmp1 := TBitmap32.Create;
  bmp1.Width := 100;
  bmp1.Height := 100;
  bmp1.FillRect(0, 0, 100, 100, clWhite32);
  bmp1.FillRect(0, 0, 80, 80, clTrGreen32);

  bmp1.Font.Size := -16;
  bmp1.Font.Color := clBlack;
  bmp1.TextOut(2, 10, 'Green');

  //Mark all fully transparent pixels (generated with TextOut) as opaque.
  TransparentToOpaque(bmp1);

  SaveBitmap32ToPNG(bmp1, 'c:\0\bmp1a.png');

  bmp2 := TBitmap32.Create;
  bmp2.Width := 80;
  bmp2.Height := 80;
  bmp2.FillRect(0, 0, 80, 80, clTrRed32);

  //Create bitmap, large enough to contain drawn text (same size as original bitmap in this example).
  bmp3 := TBitmap32.Create;
  bmp3.Width := bmp2.Width;
  bmp3.Height := bmp2.Height;

  //Copy `bmp2` to `bmp3`.
  bmp2.DrawMode := dmOpaque;
  bmp2.DrawTo(bmp3, 0, 0);

  //Mark all pixels as opaque (alpha = $FF)
  MakeOpaque(bmp3);

  //Draw text on `bmp3`. This will create proper aliasing.
  bmp3.Font.Size := -16;
  bmp3.Font.Color := clBlack;
  bmp3.TextOut(2, 50, 'Red');

  //Make all fully transparent pixels (TextOut) opaque and all fully opaque pixels
  //   (background coming from `bmp2`) transparent.
  FlipTransparency(bmp3);

  SaveBitmap32ToPNG(bmp3, 'c:\0\bmp3a.png');

  //Blend `bmp3` on semi-transparent background (`bmp2`).
  bmp3.DrawMode := dmBlend;
  bmp3.DrawTo(bmp2, 0, 0);

  SaveBitmap32ToPNG(bmp2, 'c:\0\bmp2a.png');

  //Blend background + text onto main image.
  bmp2.DrawMode := dmBlend;
  bmp2.DrawTo(bmp1, 20, 20);

  SaveBitmap32ToPNG(bmp1, 'c:\0\bmpcombineda.png');

  bmp1.Free;
  bmp2.Free;
  bmp3.Free;
end;
</code>```

Resulting images:

bmp1a:
bmp2a:
bmp3a:
bmpcombineda:

Body:
I'm trying to implement a layered painting system inside one of our internal components and I have problems blending bitmaps containing text.

Following code fragment shows the problem:

uses
  GR32;

procedure DrawBitmaps;
var
  bmp1: TBitmap32;
  bmp2: TBitmap32;
begin
  bmp1 := TBitmap32.Create;
  bmp1.Width := 100;
  bmp1.Height := 100;
  bmp1.FillRect(0, 0, 100, 100, clWhite32);
  bmp1.FillRect(0, 0, 80, 80, clTrGreen32);

  bmp1.Font.Size := -16;
  bmp1.Font.Color := clBlack;
  bmp1.TextOut(2, 10, 'Green');

  bmp1.SaveToFile('c:\0\bmp1.bmp');

  bmp2 := TBitmap32.Create;
  bmp2.Width := 80;
  bmp2.Height := 80;
  bmp2.FillRect(0, 0, 80, 80, clTrRed32);

  bmp2.Font.Size := -16;
  bmp2.Font.Color := clBlack;
  bmp2.TextOut(2, 50, 'Red');

  bmp2.SaveToFile('c:\0\bmp2.bmp');

  bmp2.DrawMode := dmBlend;
  bmp2.DrawTo(bmp1, 20, 20);

  bmp1.SaveToFile('c:\0\bmpcombined.bmp');

  bmp1.Free;
  bmp2.Free;
end;

Resulting images:

bmp1:
bmp2:
bmpcombined:

As you can see, text is painted in black on bmp and bmp2, but appears white on bmpcombined.

I'm guessing the problem lies in TextOut which maps to Windows.ExtTextOut (via GR32_Backends_VCL.pas, TGDIBackend.Textout). That method doesn't handle transparency and paints text with alpha 00 (color is $000000 instead of $FF000000).

As a quick fix, setting bmp2.Font.Color to $FF000000 doesn't help.

bmp2.Font.Color := TColor(clBlack32);

I am using fresh sources from GitHub

How should I paint a non-transparent text on a semi-transparent background so that I could blend this into a larger picture?

Body:
The best solution I could find requires three helper functions.

TransparentToOpaque changes all fully transparent pixels to opaque.

procedure TransparentToOpaque(bmp: TCustomBitmap32);
var
  I: Integer;
  D: PColor32Entry;
begin
  D := PColor32Entry(@bmp.Bits[0]);
  for I := 0 to bmp.Width * bmp.Height - 1 do begin
    if D.A = 0 then
      D.A := $FF;
    Inc(D);
  end;
  bmp.Changed;
end;

FlipTransparency changes all fully transparent pixels to opaque and vice versa.

procedure FlipTransparency(bmp: TCustomBitmap32);
var
  I: Integer;
  D: PColor32Entry;
begin
  D := PColor32Entry(@bmp.Bits[0]);
  for I := 0 to bmp.Width * bmp.Height - 1 do begin
    if D.A = 0 then
      D.A := $FF
    else if D.A = $FF then
      D.A := 0;
    Inc(D);
  end;
  bmp.Changed;
end;

MakeOpaque marks all pixels as opaque.

procedure MakeOpaque(bmp: TCustomBitmap32);
var
  I: Integer;
  D: PColor32Entry;
begin
  D := PColor32Entry(@bmp.Bits[0]);
  for I := 0 to bmp.Width * bmp.Height - 1 do begin
    D.A := $FF;
    Inc(D);
  end;
  bmp.Changed;
end;

Following tricks can then be applied.

After drawing text on the main image bmp1 which doesn't contain transparent pixels, code calls TransparentToOpaque to prevent problems with blending later on.

When drawing on a (semi)transparent bitmap bmp2, code creates yet another bitmap bmp3 and fills it with an opaque version of that (semi)transparent bitmap. This will ensure that font is aliased to correct colors in the TextOut call.

After the TextOut bmp3 contains opaque background and transparent text. FlipTransparency is then called to generate opaque text on a transparent background.

bmp3 is blended onto bmp2. This gives up opaque text on a (semi)transparent background.

bmp2 is blended onto bmp1.

Example code:

procedure TForm53.DrawBitmaps;
var
  bmp1: TBitmap32;
  bmp2: TBitmap32;
  bmp3: TBitmap32;
begin
  bmp1 := TBitmap32.Create;
  bmp1.Width := 100;
  bmp1.Height := 100;
  bmp1.FillRect(0, 0, 100, 100, clWhite32);
  bmp1.FillRect(0, 0, 80, 80, clTrGreen32);

  bmp1.Font.Size := -16;
  bmp1.Font.Color := clBlack;
  bmp1.TextOut(2, 10, 'Green');

  //Mark all fully transparent pixels (generated with TextOut) as opaque.
  TransparentToOpaque(bmp1);

  SaveBitmap32ToPNG(bmp1, 'c:\0\bmp1a.png');

  bmp2 := TBitmap32.Create;
  bmp2.Width := 80;
  bmp2.Height := 80;
  bmp2.FillRect(0, 0, 80, 80, clTrRed32);

  //Create bitmap, large enough to contain drawn text (same size as original bitmap in this example).
  bmp3 := TBitmap32.Create;
  bmp3.Width := bmp2.Width;
  bmp3.Height := bmp2.Height;

  //Copy `bmp2` to `bmp3`.
  bmp2.DrawMode := dmOpaque;
  bmp2.DrawTo(bmp3, 0, 0);

  //Mark all pixels as opaque (alpha = $FF)
  MakeOpaque(bmp3);

  //Draw text on `bmp3`. This will create proper aliasing.
  bmp3.Font.Size := -16;
  bmp3.Font.Color := clBlack;
  bmp3.TextOut(2, 50, 'Red');

  //Make all fully transparent pixels (TextOut) opaque and all fully opaque pixels
  //   (background coming from `bmp2`) transparent.
  FlipTransparency(bmp3);

  SaveBitmap32ToPNG(bmp3, 'c:\0\bmp3a.png');

  //Blend `bmp3` on semi-transparent background (`bmp2`).
  bmp3.DrawMode := dmBlend;
  bmp3.DrawTo(bmp2, 0, 0);

  SaveBitmap32ToPNG(bmp2, 'c:\0\bmp2a.png');

  //Blend background + text onto main image.
  bmp2.DrawMode := dmBlend;
  bmp2.DrawTo(bmp1, 20, 20);

  SaveBitmap32ToPNG(bmp1, 'c:\0\bmpcombineda.png');

  bmp1.Free;
  bmp2.Free;
  bmp3.Free;
end;

Resulting images:

bmp1a:
bmp2a:
bmp3a:
bmpcombineda:


问:
localStorage is not defined (Angular Universal)
I am using universal-starter as backbone.

When my client starts, it read a token about user info from localStorage.

```<code>@Injectable()
export class UserService {
  foo() {}

  bar() {}

  loadCurrentUser() {
    const token = localStorage.getItem('token');

    // do other things
  };
}
</code>```

Everything works well, however I got this in the server side (terminal) because of server rendering:

EXCEPTION: ReferenceError: localStorage is not defined

I got the idea from ng-conf-2016-universal-patterns that using Dependency Injection to solve this. But that demo is really old.

Say I have these two files now:

main.broswer.ts

```<code>export function ngApp() {
  return bootstrap(App, [
    // ...

    UserService
  ]);
}
</code>```

main.node.ts

```<code>export function ngApp(req, res) {
  const config: ExpressEngineConfig = {
    // ...
    providers: [
      // ...
      UserService
    ]
  };

  res.render('index', config);
}
</code>```

Right now they use both same UserService. Can someone give some codes to explain how to use different Dependency Injection to solve this?

If there is another better way rather than Dependency Injection, that will be cool too.

UPDATE 1 I am using Angular 2 RC4, I tried @Martin's way. But even I import it, it still gives me error in the terminal below:

Terminal (npm start)

/my-project/node_modules/@angular/core/src/di/reflective_provider.js:240
          throw new reflective_exceptions_1.NoAnnotationError(typeOrFunc, params);
          ^ Error: Cannot resolve all parameters for 'UserService'(Http, ?). Make sure that all the parameters are decorated with Inject or
  have valid type annotations and that 'UserService' is decorated with
  Injectable.

Terminal (npm run watch)

error TS2304: Cannot find name 'LocalStorage'.

I guess it is somehow duplicated with the LocalStorage from angular2-universal (although I am not using import { LocalStorage } from 'angular2-universal';), but even I tried to change mine to LocalStorage2, still not work.

And in the meanwhile, my IDE WebStorm also shows red:

BTW, I found a import { LocalStorage } from 'angular2-universal';, but not sure how to use that.

UPDATE 2, I changed to (not sure whether there is a better way):

```<code>import { Injectable, Inject } from '@angular/core';
import { Http } from '@angular/http';
import { LocalStorage } from '../../local-storage';

@Injectable()
export class UserService {
  constructor (
    private _http: Http,
    @Inject(LocalStorage) private localStorage) {}  // <- this line is new

  loadCurrentUser() {
    const token = this.localStorage.getItem('token'); // here I change from `localStorage` to `this.localStorage`

    // …
  };
}
</code>```

This solves the issue in UPADAT 1, but now I got error in the terminal:

EXCEPTION: TypeError: this.localStorage.getItem is not a function

答:
I am having a similar issue with Angular 4 + Universal following steps here to configure a SPA that can render at client side or server side.

I am using oidc-client because I need my SPA to act as an OpenId Connect/Oauth2 client for my Identity Server.

The thing is that I was having the typical problem where localStorage or sessionStorage are not defined in server side (they only exist when there's a window object, therefore it wouldn't make sense for nodeJs to have these objects).

I have unsuccessfully tried the approach to mock the localStorage or sessionStorage and use the real one when in browser and an empty one in server.

But I came to the conclusion that for my needs I don't really need localStorage or sessionStorage to do anything in server side. If executed in NodeJs, simply skip the part where sessionStorage or localStorage is used, and the execution will then happen at client-side.

This would suffice:

```<code>console.log('Window is: ' + typeof window);
    this.userManager = typeof window !== 'undefined'? new oidc.UserManager(config) : null; //just don't do anything unless there is a window object
</code>```

In client-side rendering it prints:
Window is: object

In nodeJs it prints:
Window is: undefined

The beauty of this is that Angular Universal will simply ignore the execution/rendering at server side when there is no window object, BUT that execution will be working fine when Angular Universal sends the page with javascript to the browser, therefore even if I am running my app in NodeJs eventually my browser prints the following:
Window is: object

I know this is not a proper answer for those who really need to access localStorage or sessionStorage in server side, but for most of the cases we use Angular Universal simply to render whatever is possible to render in server side, and for sending the things that can't be rendered to the browser to work normally.

Body:
I am using universal-starter as backbone.

When my client starts, it read a token about user info from localStorage.

@Injectable()
export class UserService {
  foo() {}

  bar() {}

  loadCurrentUser() {
    const token = localStorage.getItem('token');

    // do other things
  };
}

Everything works well, however I got this in the server side (terminal) because of server rendering:

EXCEPTION: ReferenceError: localStorage is not defined

I got the idea from ng-conf-2016-universal-patterns that using Dependency Injection to solve this. But that demo is really old.

Say I have these two files now:

main.broswer.ts

export function ngApp() {
  return bootstrap(App, [
    // ...

    UserService
  ]);
}

main.node.ts

export function ngApp(req, res) {
  const config: ExpressEngineConfig = {
    // ...
    providers: [
      // ...
      UserService
    ]
  };

  res.render('index', config);
}

Right now they use both same UserService. Can someone give some codes to explain how to use different Dependency Injection to solve this?

If there is another better way rather than Dependency Injection, that will be cool too.

UPDATE 1 I am using Angular 2 RC4, I tried @Martin's way. But even I import it, it still gives me error in the terminal below:

Terminal (npm start)

/my-project/node_modules/@angular/core/src/di/reflective_provider.js:240
          throw new reflective_exceptions_1.NoAnnotationError(typeOrFunc, params);
          ^ Error: Cannot resolve all parameters for 'UserService'(Http, ?). Make sure that all the parameters are decorated with Inject or
  have valid type annotations and that 'UserService' is decorated with
  Injectable.

Terminal (npm run watch)

error TS2304: Cannot find name 'LocalStorage'.

I guess it is somehow duplicated with the LocalStorage from angular2-universal (although I am not using import { LocalStorage } from 'angular2-universal';), but even I tried to change mine to LocalStorage2, still not work.

And in the meanwhile, my IDE WebStorm also shows red:

BTW, I found a import { LocalStorage } from 'angular2-universal';, but not sure how to use that.

UPDATE 2, I changed to (not sure whether there is a better way):

import { Injectable, Inject } from '@angular/core';
import { Http } from '@angular/http';
import { LocalStorage } from '../../local-storage';

@Injectable()
export class UserService {
  constructor (
    private _http: Http,
    @Inject(LocalStorage) private localStorage) {}  // <- this line is new

  loadCurrentUser() {
    const token = this.localStorage.getItem('token'); // here I change from `localStorage` to `this.localStorage`

    // …
  };
}

This solves the issue in UPADAT 1, but now I got error in the terminal:

EXCEPTION: TypeError: this.localStorage.getItem is not a function

Body:
I am having a similar issue with Angular 4 + Universal following steps here to configure a SPA that can render at client side or server side.

I am using oidc-client because I need my SPA to act as an OpenId Connect/Oauth2 client for my Identity Server.

The thing is that I was having the typical problem where localStorage or sessionStorage are not defined in server side (they only exist when there's a window object, therefore it wouldn't make sense for nodeJs to have these objects).

I have unsuccessfully tried the approach to mock the localStorage or sessionStorage and use the real one when in browser and an empty one in server.

But I came to the conclusion that for my needs I don't really need localStorage or sessionStorage to do anything in server side. If executed in NodeJs, simply skip the part where sessionStorage or localStorage is used, and the execution will then happen at client-side.

This would suffice:

console.log('Window is: ' + typeof window);
    this.userManager = typeof window !== 'undefined'? new oidc.UserManager(config) : null; //just don't do anything unless there is a window object

In client-side rendering it prints:
Window is: object

In nodeJs it prints:
Window is: undefined

The beauty of this is that Angular Universal will simply ignore the execution/rendering at server side when there is no window object, BUT that execution will be working fine when Angular Universal sends the page with javascript to the browser, therefore even if I am running my app in NodeJs eventually my browser prints the following:
Window is: object

I know this is not a proper answer for those who really need to access localStorage or sessionStorage in server side, but for most of the cases we use Angular Universal simply to render whatever is possible to render in server side, and for sending the things that can't be rendered to the browser to work normally.


问:
Exposing API Documentation Using Flask and Swagger
I have build a small service with flask and already wrote a swagger yaml file to describe it's API. How can I expose the swagger file through the flask app?

I didn't mean to expose the file itself (send_from_directory) but to create new endpoint that will show it as swagger-ui (interactive, if possible)

答: You can use Flasgger, a Flask extension that wraps Swagger UI for Flask http://github.com/rochacbruno/flasgger</p>


问:
Spark installation in windows
I followed all the steps by Frank kane on his Youtube video to install spark on my windows pc. But i get the following error-

I tweaked Environment variables and paths with no luck. My windows version is windows 10.

答:
You need to update spark path in environment variable list. you can check tutorial to set environment variable.
http://www.dowdandassociates.com/blog/content/howto-set-an-environment-variable-in-windows-command-line-and-registry/

you also need to set path for java and scala to run spark properly.

Title: Spark installation in windows


问:
Unique element in XSD schema
I'm writing a xml schema. I want some node to be unique based upon some inner element. I wrote the below schema but it is not working. I am able to add same book/employee more than once. I want my book name/employee is should be unique and through exception if someone enters duplicate element(node)
can someone help me in this? Thanks in advance.</p>

```<code><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.w3schools.com" targetNamespace="http://www.w3schools.com" elementFormDefault="unqualified">

<xs:complexType name="employee">
    <xs:sequence>
        <xs:attribute name="name" type="xs:string" use="required"/>
        <xs:attribute name="id" type="xs:string" use="required"/>
    </xs:sequence>
</xs:complexType>

<xs:complexType name="employees">
    <xs:sequence>
        <xs:element name="employees" type="employee" minOccurs="0" maxOccurs="unbounded">
            <xs:unique name="uniqueId">
                <xs:selector xpath="employee"/>
                <xs:field xpath="@id"/>
            </xs:unique>
        </xs:element>
    </xs:sequence>
</xs:complexType>

<xs:complexType name="book">
    <xs:sequence>
        <xs:attribute name="author" type="xs:string" use="required"/>
        <xs:attribute name="title" type="xs:string" use="required"/>
    </xs:sequence>
</xs:complexType>

<xs:complexType name="bookList">
    <xs:sequence>
        <xs:element name="bookList" type="book" minOccurs="0" maxOccurs="unbounded">
            <xs:unique name="uniqueBook">
                <xs:selector xpath="book"/>
                <xs:field xpath="@title"/>
            </xs:unique>
        </xs:element>
    </xs:sequence>
</xs:complexType>

<xs:element name="Library">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="bookList" type="bookList"/>
            <xs:element name="employees" type="employees"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

</xs:schema>
</code>```

答:
Your schema says that the id attribute of employee elements must be unique, but both in your schema and in your instance (posted as a comment), the employee element does not have an id attribute; instead it has a title attribute.

Furthermore, your employee and book elements are declared in the schema to be in a namespace (though this namespace is missing from your instance), and you have ignored this namespace in defining your selector/field XPath expressions in your uniqueness constraints.

Title: Unique element in XSD schema

Body:
I'm writing a xml schema. I want some node to be unique based upon some inner element. I wrote the below schema but it is not working. I am able to add same book/employee more than once. I want my book name/employee is should be unique and through exception if someone enters duplicate element(node)
can someone help me in this? Thanks in advance.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.w3schools.com" targetNamespace="http://www.w3schools.com" elementFormDefault="unqualified">

<xs:complexType name="employee">
    <xs:sequence>
        <xs:attribute name="name" type="xs:string" use="required"/>
        <xs:attribute name="id" type="xs:string" use="required"/>
    </xs:sequence>
</xs:complexType>

<xs:complexType name="employees">
    <xs:sequence>
        <xs:element name="employees" type="employee" minOccurs="0" maxOccurs="unbounded">
            <xs:unique name="uniqueId">
                <xs:selector xpath="employee"/>
                <xs:field xpath="@id"/>
            </xs:unique>
        </xs:element>
    </xs:sequence>
</xs:complexType>

<xs:complexType name="book">
    <xs:sequence>
        <xs:attribute name="author" type="xs:string" use="required"/>
        <xs:attribute name="title" type="xs:string" use="required"/>
    </xs:sequence>
</xs:complexType>

<xs:complexType name="bookList">
    <xs:sequence>
        <xs:element name="bookList" type="book" minOccurs="0" maxOccurs="unbounded">
            <xs:unique name="uniqueBook">
                <xs:selector xpath="book"/>
                <xs:field xpath="@title"/>
            </xs:unique>
        </xs:element>
    </xs:sequence>
</xs:complexType>

<xs:element name="Library">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="bookList" type="bookList"/>
            <xs:element name="employees" type="employees"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

</xs:schema>