问:
Retrofit2: Trying to Post Object which has multiple objects in it as Json?
I have Content class like that;

public class Content {

```<code>@SerializedName("id")
long id;
@SerializedName("content_type")
ContentType contentType;

long content_type_id;

@SerializedName("created_date")
Date createdDate;

@SerializedName("modified_date")
Date modifiedDate;

@SerializedName("components")
List<Component> components;

User owner;
</code>```

These User, Component and ContentType are classes that I have created. I want to convert this class into Json like that;

```<code>{
    "content_type": {
        "id": 1,
        "name": "Post",
        "components": [
            "text",
            "longtext",
            "video"
        ],
        "component_names": [
            "title",
            "body",
            "video"
        ]
    },
    "owner": {
        "url": "http://localhost:8000/users/1/",
        "id": 1,
        "username": "admin",
        "email": "admin@admin.com"
    },
    "owner_id": 1,
    "content_type_id": 1,
    "components": [
        {
            "component_type": "text",
            "order": 1,
            "type_data": {
                "data": "Amber Run - Found"
            }
        },
        {
            "component_type": "longtext",
            "order": 2,
            "type_data": {
                "data": "Warning sign"
            }
        },
        {
            "component_type": "video",
            "order": 3,
            "type_data": {
                "data": "https://www.youtube.com/watch?v=Yj6V_a1-EUA"
            }
        }
    ]
}
</code>```

If I send this raw Json data with PostMan, it works.

I am using this method in RetrofitApiService interface

```<code> @POST("group-contents/{group_id}/")
@FormUrlEncoded
Call<Content> postContent(@Path(value = "group_id", encoded = true)  long groupId, @Body Content content);
</code>```

However, I am getting this error

@Body parameters cannot be used with form or multi-part encoding.

How should I properly use retrofit to send Json objects like that?

答:
You can send that as RequestBody, and also have to remove that @FormUrlEncoded

```<code>String json = new Gson().toJson(content) //Here content is your POJO class, that to be send.

RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);

@POST("group-contents/{group_id}/")
Call<Content> postContent(@Path(value = "group_id", encoded = true)  long groupId, @Body RequestBody body);
</code>```

Body:
I have Content class like that;

public class Content {

@SerializedName("id")
long id;
@SerializedName("content_type")
ContentType contentType;

long content_type_id;

@SerializedName("created_date")
Date createdDate;

@SerializedName("modified_date")
Date modifiedDate;

@SerializedName("components")
List<Component> components;

User owner;

These User, Component and ContentType are classes that I have created. I want to convert this class into Json like that;

{
    "content_type": {
        "id": 1,
        "name": "Post",
        "components": [
            "text",
            "longtext",
            "video"
        ],
        "component_names": [
            "title",
            "body",
            "video"
        ]
    },
    "owner": {
        "url": "http://localhost:8000/users/1/",
        "id": 1,
        "username": "admin",
        "email": "admin@admin.com"
    },
    "owner_id": 1,
    "content_type_id": 1,
    "components": [
        {
            "component_type": "text",
            "order": 1,
            "type_data": {
                "data": "Amber Run - Found"
            }
        },
        {
            "component_type": "longtext",
            "order": 2,
            "type_data": {
                "data": "Warning sign"
            }
        },
        {
            "component_type": "video",
            "order": 3,
            "type_data": {
                "data": "https://www.youtube.com/watch?v=Yj6V_a1-EUA"
            }
        }
    ]
}

If I send this raw Json data with PostMan, it works.

I am using this method in RetrofitApiService interface

 @POST("group-contents/{group_id}/")
@FormUrlEncoded
Call<Content> postContent(@Path(value = "group_id", encoded = true)  long groupId, @Body Content content);

However, I am getting this error

@Body parameters cannot be used with form or multi-part encoding.

How should I properly use retrofit to send Json objects like that?

Body:
You can send that as RequestBody, and also have to remove that @FormUrlEncoded

String json = new Gson().toJson(content) //Here content is your POJO class, that to be send.

RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);

@POST("group-contents/{group_id}/")
Call<Content> postContent(@Path(value = "group_id", encoded = true)  long groupId, @Body RequestBody body);


来源: stackexchange

问:
Web service design - error code (store in source code or store in database?)
Web service error response (code/message etc) would you store it in a database? or would you keep the error response in a method.

By the time I'm done with this, there will be hundreds of error response, maybe in the future, thousands? (I dont know yet, depends how large this web service grows).

EDIT: error response is the response returned back to the application via the web service, (not to be confused with error logging).

答:
Error codes aren't designed to look good in UI when something goes wrong. Their main goal is to inform application what happened so that application could react.

If you move the error codes to the database you'll not be able to handle them unless you'll make a standard procedure of handling EVERY error code (for example log it and shutdown the application).

ContentLicense: CC BY-SA 2.5


问:
What is the fastest way to fill up disk space
I've got a big disk worth few TBs ( 5 TBs ) and i need fill up this disk space to about 95%, this is a linux centos box.

I've tried dd as in

```<code>dd if=/dev/zero of=o_File1.img bs=209715200 count=1000
</code>```

even tried running in a loop like

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

count_=0
parallel_=10

BS=2097152000
COUNT=100
while [ $count_ -lt $parallel_ ]
do
        file="Dummy_DD_BS_"$BS"_$(date +%Y%M%d%H%m%s)_$count_.img"
        echo $file
        `dd if=/dev/zero of=$file bs=$BS count=$COUNT > /dev/null 2>&1 &`
        count_=$((count_+1))
done
</code>```

but 5 TB seems like a hell lot.

is there a faster method, I'm Okay with any scripts python/perl/bash or anything, I'm looking for a fast optimized solution

Edit:

Okay so following the quickly-create-a-large-file-on-a-linux-system
 did not really solve much anything

case 1 : dd

```<code> time dd if=/dev/zero of=filename10 bs=1G count=10
    10+0 records in
    10+0 records out
    10737418240 bytes (11 GB) copied, 34.0468 s, 315 MB/s

    real    0m34.108s
    user    0m0.000s
    sys     0m13.498s
</code>```

so an estimated around 3 - 4  hours to fill this 5 TB

Case 2 : fallocate

```<code> fallocate failed: Operation not supported
   its a custom file system not the popular ext*
</code>```

Case 3 : truncate

```<code>   this is the weirdest ones
   it doesn't really fill the disk this seems to be just reserving the space for the file so definitely not suiting my requirements
</code>```

so is there a better solution or I have to live with dd or create smaller partition to test this

答:
```<code>  fallocate -l 25G file
</code>```

<p>Try this </p>

ContentLicense: CC BY-SA 3.0

Body:
I've got a big disk worth few TBs ( 5 TBs ) and i need fill up this disk space to about 95%, this is a linux centos box.

I've tried dd as in

dd if=/dev/zero of=o_File1.img bs=209715200 count=1000

even tried running in a loop like

#!/bin/bash

count_=0
parallel_=10

BS=2097152000
COUNT=100
while [ $count_ -lt $parallel_ ]
do
        file="Dummy_DD_BS_"$BS"_$(date +%Y%M%d%H%m%s)_$count_.img"
        echo $file
        `dd if=/dev/zero of=$file bs=$BS count=$COUNT > /dev/null 2>&1 &`
        count_=$((count_+1))
done

but 5 TB seems like a hell lot.

is there a faster method, I'm Okay with any scripts python/perl/bash or anything, I'm looking for a fast optimized solution

Edit:

Okay so following the quickly-create-a-large-file-on-a-linux-system
 did not really solve much anything

case 1 : dd

 time dd if=/dev/zero of=filename10 bs=1G count=10
    10+0 records in
    10+0 records out
    10737418240 bytes (11 GB) copied, 34.0468 s, 315 MB/s

    real    0m34.108s
    user    0m0.000s
    sys     0m13.498s

so an estimated around 3 - 4  hours to fill this 5 TB

Case 2 : fallocate

 fallocate failed: Operation not supported
   its a custom file system not the popular ext*

Case 3 : truncate

   this is the weirdest ones
   it doesn't really fill the disk this seems to be just reserving the space for the file so definitely not suiting my requirements

so is there a better solution or I have to live with dd or create smaller partition to test this

Body:
  fallocate -l 25G file

Try this


问:
httpd Virtual Host and domain clash
[CentOS7]
my server IP: aaa.bbb.ccc.ddd

```<code>Server Root: /var/www/html
</code>```

I've two virtual hosts:

```<code>subdoamin1.domain.tld
Document Root: /var/www/subdomain1.domain.tld/public_html

subdoamin2.domain.tld
Document Root: /var/www/subdomain2.domain.tld/public_html
</code>```

when I go to the doamin 'subdoamin1.domain.tld' or 'subdoamin2.domain.tld' I can see both the website, it's OK,
but,
when I go to the IP, it servs me the site from '/var/www/subdomain1.domain.tld/public_html'
but, I want '/var/www/html/' be served.

where is the problem?...

答:
Apache web server has a default virtualhost concept. The default virtualhost should appear firstly from all configurations.
It show the page if the target virtualhost is uncertain.
You need to create the additional virtualhost that has ServerName aaa.bbb.ccc.ddd and DocumentRoot /var/www/html

Title: httpd Virtual Host and domain clash

Body:
[CentOS7]
my server IP: aaa.bbb.ccc.ddd

Server Root: /var/www/html

I've two virtual hosts:

subdoamin1.domain.tld
Document Root: /var/www/subdomain1.domain.tld/public_html

subdoamin2.domain.tld
Document Root: /var/www/subdomain2.domain.tld/public_html

when I go to the doamin 'subdoamin1.domain.tld' or 'subdoamin2.domain.tld' I can see both the website, it's OK,
but,
when I go to the IP, it servs me the site from '/var/www/subdomain1.domain.tld/public_html'
but, I want '/var/www/html/' be served.

where is the problem?...


问:
Node.js GraphicsMagick not working ( Invalid Parameter - -resize)
I am trying to use Graphics Magick to resize an image. I have installed the latest GrapchicsMagick and ImageMagick versions. I have installed

```<code> npm install gm
 npm install im
</code>```

too. My node.js code is:

```<code>  var gm = require('gm').subClass({imageMagick: true});

  var srcPath = __dirname + '\\' + userId + '.jpg';
  var dstPath = __dirname + '\\' + userId + '-thumbnail.jpg';

  gm(srcPath)
  .resize(100, 100)
  .noProfile()
  .write(dstPath, function (err) {
    if (!err) console.log('Image resized');
    else console.log(err);
  });
</code>```

I am getting this error:

```<code> Error: Command failed: Invalid Parameter - -resize
</code>```

I am using Windows 10 and I installed .exe and npm too.

答: My problem is solved. I had to copy the identify.exe to my app folder.</p>

Body:
I am trying to use Graphics Magick to resize an image. I have installed the latest GrapchicsMagick and ImageMagick versions. I have installed

 npm install gm
 npm install im

too. My node.js code is:

  var gm = require('gm').subClass({imageMagick: true});

  var srcPath = __dirname + '\\' + userId + '.jpg';
  var dstPath = __dirname + '\\' + userId + '-thumbnail.jpg';

  gm(srcPath)
  .resize(100, 100)
  .noProfile()
  .write(dstPath, function (err) {
    if (!err) console.log('Image resized');
    else console.log(err);
  });

I am getting this error:

 Error: Command failed: Invalid Parameter - -resize

I am using Windows 10 and I installed .exe and npm too.


问:
Combine two different array in javascript
I have two array data that I want to combine into one array, the first array contain only data of date and id, the second array contain name and id.

```<code>    temp_data:[
      0:{
        id:"1"
        date:"2017-11-07"
      }
      1:{
        id:"1"
        date:"2017-11-08"
      }
      2:{
        id:"2"
        date:"2017-11-07"
      }
      3:{
        id:"2"
        date:"2017-11-08"
      }
]

name:[
      0:{
       id:"1"
       name:"Pervies, Peter"
      }
      1:{
       id:"2"
       name:"Ming, Edmund"
      }
]
</code>```

I want the data to be look like this:

```<code>    data:[
    0:{
     id:"1"
     name:"Pervies, Peter"
     details:[
        {date:"2017-11-07"},
        {date:"2017-11-08"}
     ]
    }
    1:{
     id:"2"
     name:"Ming, Edmund"
     details:[
        {date:"2017-11-07"},
        {date:"2017-11-08"}
     ]
    }
]
</code>```

I have try the code below to combine the two array,it works but not in the way I expect.

```<code>  let len = temp_data.length;
    let leng = name.length;
        for (let i = 0; i < leng; ++i) {
            for (let x = 0; x < len; ++x) {
                if (name[i].id == temp_data[x].id) {
                    let id = name[i].id;
                    let details = temp_data[x];
                    data.push({id,details})
                }
            }
        }

    // ------------------------------------------------------------------------

       let dat = temp_data,
       hash = Object.create(null),
       result = [];

   dat.forEach(function (o) {
        if (!hash[o.id]) {
         hash[o.id] = [];
         result.push(hash[o.id]);
        }
          hash[o.id].push(o);
    });

        data = result;
</code>```

can you help me with this?

答:
You can use undescore library for this task: </p>

```<code>let _ = require ('underscore');

let  temp_data =[
      {
        id:"1",
        date:"2017-11-07"
      },
      {
        id:"1",
        date:"2017-11-08"
      },
      {
        id:"2",
        date:"2017-11-07"
      },
      {
        id:"2",
        date:"2017-11-08"
      }
] ;

let name = [
      {
       id:"1",
       name:"Pervies, Peter"
      },
      {
       id:"2",
       name:"Ming, Edmund"
      }
];

temp_data = temp_data.concat(name);

let groupedTempData = _.groupBy(temp_data,function(item){
        return item.id;
});

let result = [];

_.each(groupedTempData,function(item){

    let obj = {};
    obj.details =[];

    _.each(item,function(data){
        if(data.name){
            obj.name = data.name;
        }
        if(data.date){
            obj.details.push({date:data.date});
        }
    });
    obj.id = item[0].id;

    result.push(obj);

});

console.log(JSON.stringify(result));
</code>```

Body:
I have two array data that I want to combine into one array, the first array contain only data of date and id, the second array contain name and id.

    temp_data:[
      0:{
        id:"1"
        date:"2017-11-07"
      }
      1:{
        id:"1"
        date:"2017-11-08"
      }
      2:{
        id:"2"
        date:"2017-11-07"
      }
      3:{
        id:"2"
        date:"2017-11-08"
      }
]

name:[
      0:{
       id:"1"
       name:"Pervies, Peter"
      }
      1:{
       id:"2"
       name:"Ming, Edmund"
      }
]

I want the data to be look like this:

    data:[
    0:{
     id:"1"
     name:"Pervies, Peter"
     details:[
        {date:"2017-11-07"},
        {date:"2017-11-08"}
     ]
    }
    1:{
     id:"2"
     name:"Ming, Edmund"
     details:[
        {date:"2017-11-07"},
        {date:"2017-11-08"}
     ]
    }
]

I have try the code below to combine the two array,it works but not in the way I expect.

  let len = temp_data.length;
    let leng = name.length;
        for (let i = 0; i < leng; ++i) {
            for (let x = 0; x < len; ++x) {
                if (name[i].id == temp_data[x].id) {
                    let id = name[i].id;
                    let details = temp_data[x];
                    data.push({id,details})
                }
            }
        }

    // ------------------------------------------------------------------------

       let dat = temp_data,
       hash = Object.create(null),
       result = [];

   dat.forEach(function (o) {
        if (!hash[o.id]) {
         hash[o.id] = [];
         result.push(hash[o.id]);
        }
          hash[o.id].push(o);
    });

        data = result;

can you help me with this?

Body:
You can use undescore library for this task:

let _ = require ('underscore');

let  temp_data =[
      {
        id:"1",
        date:"2017-11-07"
      },
      {
        id:"1",
        date:"2017-11-08"
      },
      {
        id:"2",
        date:"2017-11-07"
      },
      {
        id:"2",
        date:"2017-11-08"
      }
] ;

let name = [
      {
       id:"1",
       name:"Pervies, Peter"
      },
      {
       id:"2",
       name:"Ming, Edmund"
      }
];

temp_data = temp_data.concat(name);

let groupedTempData = _.groupBy(temp_data,function(item){
        return item.id;
});

let result = [];

_.each(groupedTempData,function(item){

    let obj = {};
    obj.details =[];

    _.each(item,function(data){
        if(data.name){
            obj.name = data.name;
        }
        if(data.date){
            obj.details.push({date:data.date});
        }
    });
    obj.id = item[0].id;

    result.push(obj);

});

console.log(JSON.stringify(result));


问:
image as link with javascript
I have two images and two radio buttons.

and if you click on a image the readio button will be selected.

But now I want to have the image as a link. So that you can see the hand - by normal link.

this is the html:

```<code> @if (Html.GebruikerContext().Klant.LogoIDSpecified)
                {
                    <div class="property wide extra-margin">
                        <br />
                        <label>
                            Kies header logo
                        </label>
                        <div class="email-logo">
                            <label>
                                <span class="email-logo-image">
                                     <img src='/Beheer/Images/mainlogo_274x122.png' />
                                </span>
                                <span class="email-logo-button">
                                    @Html.RadioButton("logo-selectie", "standaard", !Model.GebruikKlantLogo, new { @name = "logoKeuze" })
                                    <span>standaard logo</span>
                                </span>
                            </label>
                        </div>                        <div class="email-logo">
                            <label>
                                <span class="email-logo-image">
                                    <img src='/Beheer/Document/Download?documentID=@(Html.GebruikerContext().Klant.LogoID)' />
                                </span>
                                <span class="email-logo-button">
                                    @Html.RadioButton("logo-selectie", "klant", Model.GebruikKlantLogo, new { @name = "logoKeuze" })
                                    <span>eigen logo</span>
                                </span>
                            </label>
                        </div>
                    </div>
                }
</code>```

and this is the javascript:

```<code>$('#logo-selectie[value=standaard]').change(function () {
    $('#GebruikKlantLogo').val(false);
});

$('#logo-selectie[value=klant]').change(function () {
    $('#GebruikKlantLogo').val(true);
});
</code>```

答:
Put your image in  tag if you want to your image to act like a link.
If you just want to see "the hand" then you have to write a css

```<code>.classname {
  cursor: pointer;
}
</code>```

Title: image as link with javascript

Body:
I have two images and two radio buttons.

and if you click on a image the readio button will be selected.

But now I want to have the image as a link. So that you can see the hand - by normal link.

this is the html:

 @if (Html.GebruikerContext().Klant.LogoIDSpecified)
                {

                            Kies header logo

                                    @Html.RadioButton("logo-selectie", "standaard", !Model.GebruikKlantLogo, new { @name = "logoKeuze" })
                                    standaard logo

                                    @Html.RadioButton("logo-selectie", "klant", Model.GebruikKlantLogo, new { @name = "logoKeuze" })
                                    eigen logo

                }

and this is the javascript:

$('#logo-selectie[value=standaard]').change(function () {
    $('#GebruikKlantLogo').val(false);
});

$('#logo-selectie[value=klant]').change(function () {
    $('#GebruikKlantLogo').val(true);
});

Body:
Put your image in <a> tag if you want to your image to act like a link.
If you just want to see "the hand" then you have to write a css

.classname {
  cursor: pointer;
}

<img class="classname" src='/Beheer/Images/mainlogo_274x122.png' />


问:
Can jQuery UI 1.8.2 run on jquery 1.4.1?
It's that simple question.

Can jQuery UI 1.8.2 run on jquery 1.4.1?

答: Probably possible, but I would not recommend that. Every jQueryUI update was developed after a new jQuery release, so it's most likely that they used at least some of the new features.</p>


问:
iOS Fabric Crashlytics Answers Kit not Collecting Data

Problem Summary

UPDATE: I have fixed the issue somehow, I am not sure how. I just deleted the Apps from my dashboard, recreated them, cleaned the Fabrics and Crashlytics Cache and after four or five times trying, it started working out of its own accord. I am still interested in knowing how did it happen and how can it actually be solved without deleting the app altogether.

TL;DR I am not receiving any stats from Answers kit and it looks like Fabric thinks Answers is not installed in my App even though it is. I am not interested in events tracking, I just need the metrics stats.

Problem Explained

Fabric Crashlytics kit comes bundled together with Answers and for most of my Apps, whenever I set up Crashlytics, Answers is set up too and I can see stats on my Fabric Dashboard.

However for a couple of my apps, I can't see the stats and it seems like Answers is disabled. The Dashboard says for viewing stats, Answers is required.

But when I look at my Fabric Mac Client, It says that for this App, Answers kit is installed and enabled.

So let's head back to the web dashboard for the App, all the options for stats are disabled except Crashlytics and the App itself is kind of greyed out unlike other Apps.

And in details it first keeps waiting for "Events" and recommends that I should make a fresh installation of the App (Which I have done a number of times now).

After a while, it says no events were received and it asks me to perform a fresh install and enable debugging mode.

My Configuration

My pod file is:

```<code>pod 'Fabric'
pod 'Crashlytics'
</code>```

I am setting up my Fabric kit in AppDelegate like:

```<code>[Fabric with:@[[Crashlytics class]]];
</code>```

And I have enabled the debugging mod like:

```<code>[[Fabric sharedSDK] setDebug: YES];
</code>```

What I have done so far

Made sure Answers is installed.

Enabled debugging mode. Fabric says it can tell me if Answers is enabled and sending events but I haven't seen any log regarding it. The only three logs I receive are the version number and notifications that Settings have been downloaded and are available for consumption.

Made Fresh Installations

Checked logs of debugging mode which confirm that the settings for Fabric have been downloaded and are ready for consumption.

Added Fastlane Kit to create build deliveries to see if there was some problem with communication between my App and Fabric. The Builds are showing correctly and are being uploaded correctly but again, no Answers.

I have even logged a login event even though I don't need it, just to see if it starts transmitting Answers data.

```<code>[Answers logLoginWithMethod:@"Email"
                        success:@YES
               customAttributes:@{}];
</code>```

There is also this interesting log when App runs:

```<code>[FileManager] Failed to remove file '/var/mobile/Containers/Data/Application/F055EE71-5064-4105-B41D-BD098F28DAA9/Library/Caches/com.crashlytics.data/com.sampleapp.mysampleapp/v3/launchmarker' : Error Domain=NSCocoaErrorDomain Code=4 "“launchmarker” couldn’t be removed." UserInfo={NSUnderlyingError=0x14e6a830 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}, NSFilePath=/var/mobile/Containers/Data/Application/F055EE71-5064-4105-B41D-BD098F28DAA9/Library/Caches/com.crashlytics.data/com.sampleapp.mysampleapp/v3/launchmarker, NSUserStringVariant=(
    Remove
)}
</code>```

It pops up whenever I attempt a fresh install after resetting the simulator. Also, check the settings json in Fabrics Data in Cache. The curious bits here:

```<code>"features": {
    "collect_logged_exceptions": true,
    "collect_reports": false,
    "collect_analytics": false,
    "prompt_enabled": false,
    "push_enabled": true
  }
</code>```

Complete JSON can be seen here.

How can I fix this?

答:
I think that your AppDelegate should look like this:</p>

```<code>[Fabric with:@[[Crashlytics class], [Answers class]]];
</code>```

Body:
Problem Summary

UPDATE: I have fixed the issue somehow, I am not sure how. I just deleted the Apps from my dashboard, recreated them, cleaned the Fabrics and Crashlytics Cache and after four or five times trying, it started working out of its own accord. I am still interested in knowing how did it happen and how can it actually be solved without deleting the app altogether.

TL;DR I am not receiving any stats from Answers kit and it looks like Fabric thinks Answers is not installed in my App even though it is. I am not interested in events tracking, I just need the metrics stats.

Problem Explained

Fabric Crashlytics kit comes bundled together with Answers and for most of my Apps, whenever I set up Crashlytics, Answers is set up too and I can see stats on my Fabric Dashboard.

However for a couple of my apps, I can't see the stats and it seems like Answers is disabled. The Dashboard says for viewing stats, Answers is required.

But when I look at my Fabric Mac Client, It says that for this App, Answers kit is installed and enabled.

So let's head back to the web dashboard for the App, all the options for stats are disabled except Crashlytics and the App itself is kind of greyed out unlike other Apps.

And in details it first keeps waiting for "Events" and recommends that I should make a fresh installation of the App (Which I have done a number of times now).

After a while, it says no events were received and it asks me to perform a fresh install and enable debugging mode.

My Configuration

My pod file is:

pod 'Fabric'
pod 'Crashlytics'

I am setting up my Fabric kit in AppDelegate like:

[Fabric with:@[[Crashlytics class]]];

And I have enabled the debugging mod like:

[[Fabric sharedSDK] setDebug: YES];

What I have done so far

Made sure Answers is installed.

Enabled debugging mode. Fabric says it can tell me if Answers is enabled and sending events but I haven't seen any log regarding it. The only three logs I receive are the version number and notifications that Settings have been downloaded and are available for consumption.

Made Fresh Installations

Checked logs of debugging mode which confirm that the settings for Fabric have been downloaded and are ready for consumption.

Added Fastlane Kit to create build deliveries to see if there was some problem with communication between my App and Fabric. The Builds are showing correctly and are being uploaded correctly but again, no Answers.

I have even logged a login event even though I don't need it, just to see if it starts transmitting Answers data.

[Answers logLoginWithMethod:@"Email"
                        success:@YES
               customAttributes:@{}];

There is also this interesting log when App runs:

[FileManager] Failed to remove file '/var/mobile/Containers/Data/Application/F055EE71-5064-4105-B41D-BD098F28DAA9/Library/Caches/com.crashlytics.data/com.sampleapp.mysampleapp/v3/launchmarker' : Error Domain=NSCocoaErrorDomain Code=4 "“launchmarker” couldn’t be removed." UserInfo={NSUnderlyingError=0x14e6a830 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}, NSFilePath=/var/mobile/Containers/Data/Application/F055EE71-5064-4105-B41D-BD098F28DAA9/Library/Caches/com.crashlytics.data/com.sampleapp.mysampleapp/v3/launchmarker, NSUserStringVariant=(
    Remove
)}

It pops up whenever I attempt a fresh install after resetting the simulator. Also, check the settings json in Fabrics Data in Cache. The curious bits here:

"features": {
    "collect_logged_exceptions": true,
    "collect_reports": false,
    "collect_analytics": false,
    "prompt_enabled": false,
    "push_enabled": true
  }

Complete JSON can be seen here.

How can I fix this?

Body:
I think that your AppDelegate should look like this:

[Fabric with:@[[Crashlytics class], [Answers class]]];


问:
How to retrieve url of the image uploaded on Amazon S3
I am new to Amazon S3. I want to upload all my images / PDF to S3 and let the user access those by using the URL. I am reading up the documentation and landed on this page:

http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjSingleOpNET.html

This sample only uploads the image. How would I get the URL of the uploaded image so I can store them in my database and my user can use them to view the image?

For eg. Shouldn't it offer some url like http://aws.amazon.com/bucket-name/image-name.jpg and then I can type in that url in the browser and view my uploaded image from amazon.

Any help is appreciated.

答: You already know the bucket name, and the object name when you do the upload - S3 doesn't need to 'tell' you anything, you have the information - in fact you told S3 what the file name will be.</p>


问:
Need clarity on Webgl Shaders configuration and parameters to achieve the desired results
I want to apply wave effect on water spritesheet from top to bottom direction in way that it looks animated. I got some piece of code from internet but it's creating some effects but in random manner. I want to control it as per my requirement. Below is the code:

```<code>function CustomFilter(customSprite, ambientColor, resolution) {
        PIXI.Filter.call(
            this,
            null,
            (
                `
               varying vec2 vTextureCoord;
            uniform sampler2D uSampler;
            uniform float u_ctime;
            const int iterations = 1;
            const float view = 3.;
            void main()
            {
                    vec2 fragCoord = vTextureCoord;
                    vec2 iResolution = vec2(1.0,1.0);
                    float iGlobalTime = u_ctime;
                vec2 uv = fragCoord.xy;
                uv *= view;
                for (int i = 0; i < iterations; i++) {
                float ang = atan(uv.y+cos(uv.y*2.+iGlobalTime)*.5,
                uv.y+sin(uv.y*2.+iGlobalTime)*.5)-length(uv)*.1;
                float sn = sin(ang);

                 mat2 m = mat2(sn,sn,sn,sn);
                 uv = uv*.15-abs(uv*.5*m);
                }

                float d = length(mod(uv,1.)-.5)-.4;

                d *= 20.;
                vec4 FragColor = vec4( sin(uv.x*d), sin(d+.5346), -sin(d+uv.x*1.63), 1. )*.5;
                vec2 u_Scale = vec2(0.0,0.07)*sin(u_ctime);
                vec3 displace = FragColor.rba;
                displace.xy *= displace.z * u_Scale*(0.5-fragCoord.x);
                gl_FragColor = texture2D( uSampler, vTextureCoord + displace.xy );
            }

            `
            )

        );
</code>```

答:
The base base functions for wave effect are sin or cos, and if you look closely, you will see that your super complex shader is full of that. Paradoxically, this is way more complex to acheive randomness than a regular wave.

For example, to draw a wave along X (horizontal) axis, with variation on Y (vertical) axis, you would use this function:

```<code>let frequency = 2.0;
let amplitude = 1.0;
let y_base = 0.0;
for(x = 0.0; x < 1.0; x += 0.01) {
  point.x = x;
  point.y = y_base + (sin(x * frequency) * amplitude);
}
</code>```

Pretty simple, no ? You simply have to apply this concept to your shader, for example, with texture sampling. So, if you want, for example, create a wave effect along X axis, you can use something like that:

```<code> float f = 5.0;
 float a = 0.05;
 vec4 waved = texture2D(sampler, vec2(coord.x, coord.y+(sin(coord.x*f)*a)));
</code>```

If you want add some animation, you simply have to add a kind of time variable (in your shader, this is currently u_ctime), and the pseudo-code will look like this:

```<code>let time = clock();
let pitch = 0.5;
let frequency = 2.0;
let amplitude = 1.0;
let y_base = 0.0;

for(x = 0.0; x < 1.0; x += 0.01) {
  point.x = x;
  point.y = y_base + (sin((time * pitch) + x * frequency) * amplitude);
}
</code>```

See also: https://en.wikipedia.org/wiki/Sine#Unit_circle_definition

Body:
I want to apply wave effect on water spritesheet from top to bottom direction in way that it looks animated. I got some piece of code from internet but it's creating some effects but in random manner. I want to control it as per my requirement. Below is the code:

function CustomFilter(customSprite, ambientColor, resolution) {
        PIXI.Filter.call(
            this,
            null,
            (
                `
               varying vec2 vTextureCoord;
            uniform sampler2D uSampler;
            uniform float u_ctime;
            const int iterations = 1;
            const float view = 3.;
            void main()
            {
                    vec2 fragCoord = vTextureCoord;
                    vec2 iResolution = vec2(1.0,1.0);
                    float iGlobalTime = u_ctime;
                vec2 uv = fragCoord.xy;
                uv *= view;
                for (int i = 0; i < iterations; i++) {
                float ang = atan(uv.y+cos(uv.y*2.+iGlobalTime)*.5,
                uv.y+sin(uv.y*2.+iGlobalTime)*.5)-length(uv)*.1;
                float sn = sin(ang);

                 mat2 m = mat2(sn,sn,sn,sn);
                 uv = uv*.15-abs(uv*.5*m);
                }

                float d = length(mod(uv,1.)-.5)-.4;

                d *= 20.;
                vec4 FragColor = vec4( sin(uv.x*d), sin(d+.5346), -sin(d+uv.x*1.63), 1. )*.5;
                vec2 u_Scale = vec2(0.0,0.07)*sin(u_ctime);
                vec3 displace = FragColor.rba;
                displace.xy *= displace.z * u_Scale*(0.5-fragCoord.x);
                gl_FragColor = texture2D( uSampler, vTextureCoord + displace.xy );
            }

            `
            )

        );

Body:
The base base functions for wave effect are sin or cos, and if you look closely, you will see that your super complex shader is full of that. Paradoxically, this is way more complex to acheive randomness than a regular wave.

For example, to draw a wave along X (horizontal) axis, with variation on Y (vertical) axis, you would use this function:

let frequency = 2.0;
let amplitude = 1.0;
let y_base = 0.0;
for(x = 0.0; x < 1.0; x += 0.01) {
  point.x = x;
  point.y = y_base + (sin(x * frequency) * amplitude);
}

Pretty simple, no ? You simply have to apply this concept to your shader, for example, with texture sampling. So, if you want, for example, create a wave effect along X axis, you can use something like that:

 float f = 5.0;
 float a = 0.05;
 vec4 waved = texture2D(sampler, vec2(coord.x, coord.y+(sin(coord.x*f)*a)));

If you want add some animation, you simply have to add a kind of time variable (in your shader, this is currently u_ctime), and the pseudo-code will look like this:

let time = clock();
let pitch = 0.5;
let frequency = 2.0;
let amplitude = 1.0;
let y_base = 0.0;

for(x = 0.0; x < 1.0; x += 0.01) {
  point.x = x;
  point.y = y_base + (sin((time * pitch) + x * frequency) * amplitude);
}

See also: https://en.wikipedia.org/wiki/Sine#Unit_circle_definition


问:
Java exceptions wrapping: bad practice?
Coming from a PHP world where there's only one way to write exceptions handling.. I found the wrapping of exceptions in Java a bit "ugly":

```<code>public void exampleOneException(String input) throws MyBusinessException {
    try {
        // do something
    } catch (NumberFormatException e) {
        throw new MyBusinessException("Error...", e);
    }
}
</code>```

I prefer to use this style instead:

```<code>public void exampleTwoException() {
    try {
        // do something
    } catch (MyBusinessException e) {
        log.error("Error...: " + e);
    } catch (NumberFormatException e) {
        log.error("Error...: " + e);
    }
}
</code>```

Is there any difference or best practices on those approaches on handling exceptions?

答:
From the perspective of clean and solid code you are not driving to the right direction.

Firstly you do not need to use try/catch for an Exception that is already thrown by the method's header. So in your first case the code should be like below:

```<code> public void exampleOneException(String input) throws MyBusinessException {
    // do something
 }
</code>```

This is prettier isn't it?
In the above case, if the MyBusinessException would occur then the exception will be swallowed so the user will never see what happened. If you want this to happen then this is your best practice.

The second case is clear. You catch two different exceptions and you handle them
(by logging) which is a better practice generally speaking.

So the best practice of your two different cases depends on what you want to achieve. Regarding beauty, this is totally subjective.

Title: Java exceptions wrapping: bad practice?

Body:
Coming from a PHP world where there's only one way to write exceptions handling.. I found the wrapping of exceptions in Java a bit "ugly":

public void exampleOneException(String input) throws MyBusinessException {
    try {
        // do something
    } catch (NumberFormatException e) {
        throw new MyBusinessException("Error...", e);
    }
}

I prefer to use this style instead:

public void exampleTwoException() {
    try {
        // do something
    } catch (MyBusinessException e) {
        log.error("Error...: " + e);
    } catch (NumberFormatException e) {
        log.error("Error...: " + e);
    }
}

Is there any difference or best practices on those approaches on handling exceptions?

Body:
From the perspective of clean and solid code you are not driving to the right direction.

Firstly you do not need to use try/catch for an Exception that is already thrown by the method's header. So in your first case the code should be like below:

 public void exampleOneException(String input) throws MyBusinessException {
    // do something
 }

This is prettier isn't it?
In the above case, if the MyBusinessException would occur then the exception will be swallowed so the user will never see what happened. If you want this to happen then this is your best practice.

The second case is clear. You catch two different exceptions and you handle them
(by logging) which is a better practice generally speaking.

So the best practice of your two different cases depends on what you want to achieve. Regarding beauty, this is totally subjective.


问:
APPIUM ANDROID TESTING- using webdriver
In appium if we are using Android driver, we can use swipe to scroll the screen.
But,iam using webdriver, how to scroll the screen in android if webdriver is used?

答:
You can perform swipe by using following code to swipe / scroll up:

```<code>Dimension size = this.driver.manage ()
    .window ()
    .getSize ();
int startX = size.getWidth () / 2;
int startY = size.getHeight () / 2;
int endX = 0;
int endY = (int) (startY * -1 * 0.5);
TouchAction action = new TouchAction (this.driver);
action.press (startX, startY)
    .moveTo (endX, endY)
    .release ()
    .perform ();
</code>```

Note:

Even if you use AndroidDriver, in latest release of Appium Java client or any other client, they have removed swipe, zoom and similar other methods. So you need to do it yourself like in the example above.

Title: APPIUM ANDROID TESTING- using webdriver

Body:
You can perform swipe by using following code to swipe / scroll up:

Dimension size = this.driver.manage ()
    .window ()
    .getSize ();
int startX = size.getWidth () / 2;
int startY = size.getHeight () / 2;
int endX = 0;
int endY = (int) (startY * -1 * 0.5);
TouchAction action = new TouchAction (this.driver);
action.press (startX, startY)
    .moveTo (endX, endY)
    .release ()
    .perform ();

Note:

Even if you use AndroidDriver, in latest release of Appium Java client or any other client, they have removed swipe, zoom and similar other methods. So you need to do it yourself like in the example above.


问:
Linq To SQLite with NHibernate
I use NHibernate Mapping and SQLite for db.
Part of linq expression works good, but the others like FirstOrDefault() or Take() doesn't work.
because the Linq generated to select Top(x or 1),
and SQLite works with LIMIT

the config:

<session-factory name="ScenarioTest">
      <property name="connection.release_mode">after_transaction</property>
      <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
      <property name="prepare_sql">true</property>
      <property name="show_sql">true</property>
      <property name="format_sql">false</property>
      <property name="generate_statistics">true</property>
      <property name="query.startup_check">false</property>
      <property name="adonet.batch_size">10</property>
      <property name="connection.driver_class">NHibernate.Driver.SQLite20Driver</property>
      <property name="connection.connection_string">Data Source=|DataDirectory|dev.db;Default Lock Timeout=2000000;Version=3;New=True</property>

      <property name="dialect">NHibernate.Dialect.SQLiteDialect</property>

      <property name="command_timeout">444</property>
      <property name="query.substitutions">true 1, false 0, yes 'Y', no 'N'</property>
      <property name="adonet.wrap_result_sets">false</property>
      <property name="default_schema"></property>
      <property name="query.factory_class">NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory, NHibernate</property>
    </session-factory>

There is a solution?

答:
Ok, I found the problem...
Someone added a new custom dialect to SQL Server 2008 in the code, and it's override the SQLiteDialect.

Thanks.

Title: Linq To SQLite with NHibernate


问:
Maya Python get reference paths
Hey I am writing a tool that reads all current references in the scene. Iam creating a textfield and radiobuttons for each of the references. Now I want to check the filepath of the reference for newer versions. If there is a new version it should paint the textfield yellow.

How do I get the paths for each reference? I wonder if there is any build in thing in maya which gives the path to a reference currently loaded in maya. I want to check within the loop below for each reference in referenceList

```<code>#get references
referenceList = cmds.ls(rf = True)

for reference in referenceList:
    print reference

    cmds.textField(reference)
    cmds.radioCollection()
    cmds.radioButton(label = '')
    cmds.radioButton(label = '')
    cmds.textField(reference, edit = True, text = reference)

    # newVersionFound = False
    if newVersionFound == True:
        cmds.textField(reference, edit = True, backgroundColor = [0.6,0.5,0])
</code>```

If there is no quick solution I will probably go with building the path string based on the reference name since our pipeline would allow this.

Greetings, and have a nice day!

答:
Uff can I downvote my own question?

Solution: referenceQuery does what i want.

```<code>cmds.referenceQuery('reference', filename = True)
</code>```

Title: Maya Python get reference paths

Body:
Hey I am writing a tool that reads all current references in the scene. Iam creating a textfield and radiobuttons for each of the references. Now I want to check the filepath of the reference for newer versions. If there is a new version it should paint the textfield yellow.

How do I get the paths for each reference? I wonder if there is any build in thing in maya which gives the path to a reference currently loaded in maya. I want to check within the loop below for each reference in referenceList

#get references
referenceList = cmds.ls(rf = True)

for reference in referenceList:
    print reference

    cmds.textField(reference)
    cmds.radioCollection()
    cmds.radioButton(label = '')
    cmds.radioButton(label = '')
    cmds.textField(reference, edit = True, text = reference)

    # newVersionFound = False
    if newVersionFound == True:
        cmds.textField(reference, edit = True, backgroundColor = [0.6,0.5,0])

If there is no quick solution I will probably go with building the path string based on the reference name since our pipeline would allow this.

Greetings, and have a nice day!

Body:
Uff can I downvote my own question?

Solution: referenceQuery does what i want.

cmds.referenceQuery('reference', filename = True)


问:
How can I store a function inside record/data type in Agda?
I've read the doc. It says:

The strict positivity condition rules out declarations such as

```<code>data Bad : Set where
    bad : (Bad → Bad) → Bad
    --     A     B      C
    -- A is in a negative position, B and C are OK
</code>```

since there is a negative occurrence of Bad in the type of the argument of the constructor. (Note that the corresponding data type declaration of Bad is allowed in standard functional languages such as Haskell and ML.).

But it didn't say if there's an alternative way to store a function inside something else (like a data type or a record type).

I've also tried this, which does not compile as well:

```<code>bin-op : ∀ {ℓ} (A : Set ℓ) → Set ℓ
bin-op A = A → A → A

record Storer {ℓ} (A : Set ℓ) : Set where
  field
    operator : bin-op A
</code>```

So how can I store a function inside a data type/record type/something else I don't know?

答:
The problem is in the

```<code>record Storer {ℓ} (A : Set ℓ) : Set where
</code>```

part. Here you state that Storer belongs to the Set universe, however Storer contains bin-op A which is in the Set ℓ universe, and a record can't be smaller than its fields. Hence the fix is to define Storer to be in Set ℓ:

```<code>record Storer {ℓ} (A : Set ℓ) : Set ℓ where
</code>```

Strict positivity is completely unrelated to the problem.

Universe polymorphism in Agda is described in the old wiki.

Body:
I've read the doc. It says:

The strict positivity condition rules out declarations such as

data Bad : Set where
    bad : (Bad → Bad) → Bad
    --     A     B      C
    -- A is in a negative position, B and C are OK

since there is a negative occurrence of Bad in the type of the argument of the constructor. (Note that the corresponding data type declaration of Bad is allowed in standard functional languages such as Haskell and ML.).

But it didn't say if there's an alternative way to store a function inside something else (like a data type or a record type).

I've also tried this, which does not compile as well:

bin-op : ∀ {ℓ} (A : Set ℓ) → Set ℓ
bin-op A = A → A → A

record Storer {ℓ} (A : Set ℓ) : Set where
  field
    operator : bin-op A

So how can I store a function inside a data type/record type/something else I don't know?

Body:
The problem is in the

record Storer {ℓ} (A : Set ℓ) : Set where

part. Here you state that Storer belongs to the Set universe, however Storer contains bin-op A which is in the Set ℓ universe, and a record can't be smaller than its fields. Hence the fix is to define Storer to be in Set ℓ:

record Storer {ℓ} (A : Set ℓ) : Set ℓ where

Strict positivity is completely unrelated to the problem.

Universe polymorphism in Agda is described in the old wiki.


问:
Extract text from html tags using reduce in Javascript
I'm trying to concatenate the inner HTML of each paragraph tag on my page in one single string using reduce. Here's my try:

// JS
let par = Array.from(document.getElementsByTagName("p"));
document.write(par.reduce((a, b) => a + ", " + b.innerHTML));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- HTML -->
<p>Apple</p>
<p>Strawberry</p>
<p>Banana</p></code>```

And here's the (wrong) output:

[object HTMLParagraphElement], Strawberry, Banana

What am I doing wrong?

Many thanks for your help!

答:
A good solution would be to use map to create an array containing the actual content of your paragraphs.

Then by using reduce, passing the empty string as the accumulator (2nd argument), you can get string combining the contents.

Script:

/* Cache the p elements found. */
let pElems = document.getElementsByTagName("p");

/* Create an array containing the innerHTML of each 'p' element. */
let par = [].map.call(pElems, (a)=>a.innerHTML);

/* Use 'reduce' to combine them (passing the emoty string as the accumulator. */
document.write(par.reduce((a, b) => a + ", " + b), "");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- HTML -->
<p>Apple</p>
<p>Strawberry</p>
<p>Banana</p></code>```

One-liner:

document.write([].map.call(document.getElementsByTagName("p"), (a)=>a.innerHTML).reduce((a, b) => a + ", " + b), "");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- HTML -->
<p>Apple</p>
<p>Strawberry</p>
<p>Banana</p></code>```

Body:
I'm trying to concatenate the inner HTML of each paragraph tag on my page in one single string using reduce. Here's my try:

// JS
let par = Array.from(document.getElementsByTagName("p"));
document.write(par.reduce((a, b) => a + ", " + b.innerHTML));

Apple

Strawberry

Banana

And here's the (wrong) output:

[object HTMLParagraphElement], Strawberry, Banana

What am I doing wrong?

Many thanks for your help!

Body:
A good solution would be to use map to create an array containing the actual content of your paragraphs.

Then by using reduce, passing the empty string as the accumulator (2nd argument), you can get string combining the contents.

Script:

/* Cache the p elements found. */
let pElems = document.getElementsByTagName("p");

/* Create an array containing the innerHTML of each 'p' element. */
let par = [].map.call(pElems, (a)=>a.innerHTML);

/* Use 'reduce' to combine them (passing the emoty string as the accumulator. */
document.write(par.reduce((a, b) => a + ", " + b), "");

<!-- HTML -->
<p>Apple</p>
<p>Strawberry</p>
<p>Banana</p>

One-liner:

document.write([].map.call(document.getElementsByTagName("p"), (a)=>a.innerHTML).reduce((a, b) => a + ", " + b), "");

<!-- HTML -->
<p>Apple</p>
<p>Strawberry</p>
<p>Banana</p>


问:
How to write a bash script to give another program response
I have a bash script that does several tasks, including python manage.py syncdb on a fresh database. This command asks for input, like the login info for the admin. Currently, I just type this into the command line every time. Is there a way I can automatically provide these replies as part of the bash script?

Thanks, I don't really know anything about bash.

I'm using Ubuntu 10.10.

答:
I answered a similar question on SF, but this one is more general, and it's good to have on SO.

"You want to use expect for this. It's probably already on your machine [try which expect]. It's the standard tool for any kind of interactive command-line automation. It's a Tcl library, so you'll get some Tcl skills along the way for free. Beware; it's addictive."

I should mention in this case that there is also pexpect, which is a Python expect-alike.

```<code>#!/path/to/expect
spawn python manage.py syncdb
expect "login:*"
send -- "myuser\r"
expect "*ssword:*"
send -- "mypass\r"
interact
</code>```

Body:
I answered a similar question on SF, but this one is more general, and it's good to have on SO.

"You want to use expect for this. It's probably already on your machine [try which expect]. It's the standard tool for any kind of interactive command-line automation. It's a Tcl library, so you'll get some Tcl skills along the way for free. Beware; it's addictive."

I should mention in this case that there is also pexpect, which is a Python expect-alike.

#!/path/to/expect
spawn python manage.py syncdb
expect "login:*"
send -- "myuser\r"
expect "*ssword:*"
send -- "mypass\r"
interact


答:
Try a zip bomb
You can probably download it from various places online</p>

Title: What is the fastest way to fill up disk space

Body:
I've got a big disk worth few TBs ( 5 TBs ) and i need fill up this disk space to about 95%, this is a linux centos box.

I've tried dd as in

dd if=/dev/zero of=o_File1.img bs=209715200 count=1000

even tried running in a loop like

#!/bin/bash

count_=0
parallel_=10

BS=2097152000
COUNT=100
while [ $count_ -lt $parallel_ ]
do
        file="Dummy_DD_BS_"$BS"_$(date +%Y%M%d%H%m%s)_$count_.img"
        echo $file
        `dd if=/dev/zero of=$file bs=$BS count=$COUNT > /dev/null 2>&1 &`
        count_=$((count_+1))
done

but 5 TB seems like a hell lot.

is there a faster method, I'm Okay with any scripts python/perl/bash or anything, I'm looking for a fast optimized solution

Edit:

Okay so following the quickly-create-a-large-file-on-a-linux-system
 did not really solve much anything

case 1 : dd

 time dd if=/dev/zero of=filename10 bs=1G count=10
    10+0 records in
    10+0 records out
    10737418240 bytes (11 GB) copied, 34.0468 s, 315 MB/s

    real    0m34.108s
    user    0m0.000s
    sys     0m13.498s

so an estimated around 3 - 4  hours to fill this 5 TB

Case 2 : fallocate

 fallocate failed: Operation not supported
   its a custom file system not the popular ext*

Case 3 : truncate

   this is the weirdest ones
   it doesn't really fill the disk this seems to be just reserving the space for the file so definitely not suiting my requirements

so is there a better solution or I have to live with dd or create smaller partition to test this


问:
Is there a way to change the passwords of all the nodes in a neo4j causal cluster?
I have tried using curl to change the password :

curl -H "Content-Type: application/json" -XPOST -d '{"password":"new_password"}' -u neo4j:old_password http://core_server1_ip:10003/user/neo4j/password

but I had to do it for each node, separately.

Edit : I'm using neo4j enterprise 3.3.0

答:
The native auth provider store user's information in a file located here : NEO4J_HOME/data/dbms/auth, and each node has its own.

So to change the password of a user, yes you have to do it on each node.

If you want to do it just once, there is some solutions explained in the documentation : https://neo4j.com/docs/operations-manual/current/security/authentication-authorization/native-user-role-management/propagate-users-and-roles/

To propagate changes to native users, custom roles, and role
  assignments across a cluster, there are three options:

Manually copy users and roles files on disk to all other cluster
  instances Use a shared network folder to store users and roles files
  Create an automated process that synchronizes the stored data across
  the cluster using, for example, a combination of rsync and crontab We
  note that the recommended solution for clustered security is to use
  the LDAP or plugin auth provider.

Cheers


问:
Read Log file through batch untill Keyword "Terminate" is found
I am new to batch programming and I am executing a windows batch command through jenkins on the target Windows machine.
My requirement is to read the log file ( aut.log ) while the automation is running. Once keyword "Terminate' is written in the log file, it should stop reading log and proceed to the next step. </p>

答:
I am going to give an answer based on the very unclear question.

```<code>@echo off
:start
FIND /C /I "Terminate" "F:\aut.log"
IF %ERRORLEVEL%==0 (echo found word Terminate
) else (
  goto start
)
</code>```

This will do a find in the file for the word Terminate in a loop until it is found and then echo found word Terminate at this point you will replace the echo command with your command. if however the word is not found, it will return to to :start to try again and continue forever until the word is found.

If you want to slow down the process, below :start, add timeout /t 1 for a 1 second time out.

```<code>@echo off
:start
timeout /t 1
FIND /C /I "Terminate" "F:\aut.log"
IF %ERRORLEVEL%==0 (echo found word Terminate
) else (
  goto start
)
</code>```

Finally, if you do not want to see the actual output on screen of the loop while running, you can push output to null with 1>null

```<code>@echo off
:start
FIND /C /I "Terminate" "F:\aut.log" 1>null
IF %ERRORLEVEL%==0 (echo found word Terminate
) else (
  goto start:
)
</code>```

Body:
I am going to give an answer based on the very unclear question.

@echo off
:start
FIND /C /I "Terminate" "F:\aut.log"
IF %ERRORLEVEL%==0 (echo found word Terminate
) else (
  goto start
)

This will do a find in the file for the word Terminate in a loop until it is found and then echo found word Terminate at this point you will replace the echo command with your command. if however the word is not found, it will return to to :start to try again and continue forever until the word is found.

If you want to slow down the process, below :start, add timeout /t 1 for a 1 second time out.

@echo off
:start
timeout /t 1
FIND /C /I "Terminate" "F:\aut.log"
IF %ERRORLEVEL%==0 (echo found word Terminate
) else (
  goto start
)

Finally, if you do not want to see the actual output on screen of the loop while running, you can push output to null with 1>null

@echo off
:start
FIND /C /I "Terminate" "F:\aut.log" 1>null
IF %ERRORLEVEL%==0 (echo found word Terminate
) else (
  goto start:
)


问:
normalize data in php and mysql
I want to do normalization on data that I have

I wrote the following code but it always fill the db with 0s and it shows the following error message. Fatal error: Uncaught exception you have an error in your sql syntax

```<code> // normalizaiton
$queryNorm0= $this->db->query("SELECT score from score where customer_id =".$customer_id." ");
foreach ($queryNorm0->rows as $scoreV)
{
    $scoreValue= $scoreV['score'];

    $queryNorm= $this->db->query(" SELECT MIN(`score`) as mins, MAX(`score`) as maxs FROM score WHERE customer_id= ".$customer_id."");
if($queryNorm->num_rows > 0)
{
$normValue= ($scoreValue - $queryNorm->row['mins'])/ (($queryNorm->row['maxs']) - ($queryNorm->row['mins']) );
    $queryNorm2= $this->db->query("insert into score set normalized= ".$normValue." WHERE score= ".$scoreValue."");
}
}
</code>```

any help?

答:
Updated

```<code> $mysqli = new mysqli($hostname, $username, $password, $dbname);
    $customer_id='Your_Customer_Id';
    $query = "SELECT score from score where customer_id =?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("s", $customer_id);
    $stmt->execute();
    $res = $stmt->get_result();
    $data = $res->fetch_all();;
</code>```

This code is using prepared statement. It is more safe and ensures that you will not escape your query. The problem in your code was that the double-quotes you were using were escaping your query. That's where the error was coming from. Have a look also in this link for prepared statements

Title: normalize data in php and mysql

Body:
I want to do normalization on data that I have

I wrote the following code but it always fill the db with 0s and it shows the following error message. Fatal error: Uncaught exception you have an error in your sql syntax

 // normalizaiton
$queryNorm0= $this->db->query("SELECT score from score where customer_id =".$customer_id." ");
foreach ($queryNorm0->rows as $scoreV)
{
    $scoreValue= $scoreV['score'];

    $queryNorm= $this->db->query(" SELECT MIN(`score`) as mins, MAX(`score`) as maxs FROM score WHERE customer_id= ".$customer_id."");
if($queryNorm->num_rows > 0)
{
$normValue= ($scoreValue - $queryNorm->row['mins'])/ (($queryNorm->row['maxs']) - ($queryNorm->row['mins']) );
    $queryNorm2= $this->db->query("insert into score set normalized= ".$normValue." WHERE score= ".$scoreValue."");
}
}

any help?

Body:
Updated

 $mysqli = new mysqli($hostname, $username, $password, $dbname);
    $customer_id='Your_Customer_Id';
    $query = "SELECT score from score where customer_id =?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("s", $customer_id);
    $stmt->execute();
    $res = $stmt->get_result();
    $data = $res->fetch_all();;

This code is using prepared statement. It is more safe and ensures that you will not escape your query. The problem in your code was that the double-quotes you were using were escaping your query. That's where the error was coming from. Have a look also in this link for prepared statements


问:
Angular 2 / 4 / 5 reactive forms validation - how to make it more concise?
EDIT 2:

I have created an issue for the angular team to simplify the form validation. Give it thumbs up if you want a simpler form validation experience.

https://github.com/angular/angular/issues/20477

EDIT 1:

The answer from H.abidi goes in the desired direction, but it only works for material components. In other words, I think the material also recognized this problem and they solved it for their components.

ORIGINAL QUESTION:

This is an example of an input field without validation CSS styles or error messages (e.g. red border on input field when invalid):

```<code>    <input required type="date" id="Rechnungsdatum" name="Rechnungsdatum" formControlName="Rechnungsdatum">
    <label for="Rechnungsdatum">Rechnungsdatum*</label>
</code>```

A similar input field with validation, where I apply CSS classes such as "valid valid--inline" or "invalid invalid-inline" via [ngClass] and where I display error messages and error icons looks like:

```<code>    <input required type="text" id="Rechnungsnummer" name="Rechnungsnummer" formControlName="Rechnungsnummer" [ngClass]="{'invalid invalid--inline': !signupForm.get('Rechnungsnummer').valid && (signupForm.get('Rechnungsnummer').touched || formDir.submitted),
    'valid valid--inline': signupForm.get('Rechnungsnummer').valid && (signupForm.get('Rechnungsnummer').touched || formDir.submitted)}">
    <label for="Rechnungsnummer">Rechnungsnummer*</label>
    <div class="message" *ngIf="!signupForm.get('Rechnungsnummer').valid && !signupForm.get('Rechnungsnummer').errors['required'] && (signupForm.get('Rechnungsnummer').touched || formDir.submitted)">
      <i class="icon icon-026-exclamation-mark-circle" aria-hidden="true"></i>
      Rechnungsnummer muss zwischen 3 und 6 Zeichen lang sein
    </div>
    <div class="message" *ngIf="signupForm.get('Rechnungsnummer').errors['required'] && (signupForm.get('Rechnungsnummer').touched || formDir.submitted)">
      <i class="icon icon-026-exclamation-mark-circle" aria-hidden="true"></i>
      Rechnungsnummer erforderlich
    </div>
</code>```

The code:

```<code>!signupForm.get('Rechnungsnummer').valid && (signupForm.get('Rechnungsnummer').touched || formDir.submitted)
</code>```

is repetitive. Is there a best practice to make this more concise? Or even to define some rules based on which CSS classes are added and error messages are displayed. I have a feeling that this is too much logic inside the template.

Additionally is it possible to avoid specifying the name of the form control for every input? E.g. instead of

```<code>signupForm.get('Rechnungsnummer').valid
</code>```

have something like

```<code>signupForm.currentFormControl.valid
</code>```

or like

```<code><input id="1" #thisInput [ngClass]="{valid: thisInput.valid}>
<input id="2" #thisInput [ngClass]="{valid: thisInput.valid}>
</code>```

答:
Hello With angular 5 you can use an ErrorStateMatcher.

Here's an example of use :

```<code>import {Component} from '@angular/core';
import {FormControl, FormGroupDirective, NgForm, Validators} from '@angular/forms';
import {ErrorStateMatcher} from '@angular/material/core';

/** Error when invalid control is dirty, touched, or submitted. */
export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const isSubmitted = form && form.submitted;
    return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
  }
}

/** @title Input with a custom ErrorStateMatcher */
@Component({
  selector: 'input-error-state-matcher-example',
  templateUrl: './input-error-state-matcher-example.html',
  styleUrls: ['./input-error-state-matcher-example.css'],
})
export class InputErrorStateMatcherExample {
  emailFormControl = new FormControl('', [
    Validators.required,
    Validators.email,
  ]);

  matcher = new MyErrorStateMatcher();
}
</code>```

and in yur html you use something like this :

```<code><form class="example-form">
  <mat-form-field class="example-full-width">
    <input matInput placeholder="Email" [formControl]="emailFormControl"
           [errorStateMatcher]="matcher">
    <mat-hint>Errors appear instantly!</mat-hint>
    <mat-error *ngIf="emailFormControl.hasError('email') && !emailFormControl.hasError('required')">
      Please enter a valid email address
    </mat-error>
    <mat-error *ngIf="emailFormControl.hasError('required')">
      Email is <strong>required</strong>
    </mat-error>
  </mat-form-field>
</form>
</code>```

I hope thois could help.

Body:
EDIT 2:

I have created an issue for the angular team to simplify the form validation. Give it thumbs up if you want a simpler form validation experience.

https://github.com/angular/angular/issues/20477

EDIT 1:

The answer from H.abidi goes in the desired direction, but it only works for material components. In other words, I think the material also recognized this problem and they solved it for their components.

ORIGINAL QUESTION:

This is an example of an input field without validation CSS styles or error messages (e.g. red border on input field when invalid):

    <input required type="date" id="Rechnungsdatum" name="Rechnungsdatum" formControlName="Rechnungsdatum">
    Rechnungsdatum*

A similar input field with validation, where I apply CSS classes such as "valid valid--inline" or "invalid invalid-inline" via [ngClass] and where I display error messages and error icons looks like:

    <input required type="text" id="Rechnungsnummer" name="Rechnungsnummer" formControlName="Rechnungsnummer" [ngClass]="{'invalid invalid--inline': !signupForm.get('Rechnungsnummer').valid && (signupForm.get('Rechnungsnummer').touched || formDir.submitted),
    'valid valid--inline': signupForm.get('Rechnungsnummer').valid && (signupForm.get('Rechnungsnummer').touched || formDir.submitted)}">
    Rechnungsnummer*

      Rechnungsnummer muss zwischen 3 und 6 Zeichen lang sein

      Rechnungsnummer erforderlich

The code:

!signupForm.get('Rechnungsnummer').valid && (signupForm.get('Rechnungsnummer').touched || formDir.submitted)

is repetitive. Is there a best practice to make this more concise? Or even to define some rules based on which CSS classes are added and error messages are displayed. I have a feeling that this is too much logic inside the template.

Additionally is it possible to avoid specifying the name of the form control for every input? E.g. instead of

signupForm.get('Rechnungsnummer').valid

have something like

signupForm.currentFormControl.valid

or like

<input id="1" #thisInput [ngClass]="{valid: thisInput.valid}>
<input id="2" #thisInput [ngClass]="{valid: thisInput.valid}>

Body:
Hello With angular 5 you can use an ErrorStateMatcher.

Here's an example of use :

import {Component} from '@angular/core';
import {FormControl, FormGroupDirective, NgForm, Validators} from '@angular/forms';
import {ErrorStateMatcher} from '@angular/material/core';

/** Error when invalid control is dirty, touched, or submitted. */
export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const isSubmitted = form && form.submitted;
    return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
  }
}

/** @title Input with a custom ErrorStateMatcher */
@Component({
  selector: 'input-error-state-matcher-example',
  templateUrl: './input-error-state-matcher-example.html',
  styleUrls: ['./input-error-state-matcher-example.css'],
})
export class InputErrorStateMatcherExample {
  emailFormControl = new FormControl('', [
    Validators.required,
    Validators.email,
  ]);

  matcher = new MyErrorStateMatcher();
}

and in yur html you use something like this :

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input matInput placeholder="Email" [formControl]="emailFormControl"
           [errorStateMatcher]="matcher">
    <mat-hint>Errors appear instantly!</mat-hint>
    <mat-error *ngIf="emailFormControl.hasError('email') && !emailFormControl.hasError('required')">
      Please enter a valid email address
    </mat-error>
    <mat-error *ngIf="emailFormControl.hasError('required')">
      Email is <strong>required</strong>
    </mat-error>
  </mat-form-field>
</form>

I hope thois could help.


问:
How do you play a single NetStream but show different parts of it on different video objects?
I have 3D videos encoded with each eye's content side-by-side on each frame. What I want to do is take the left-half and over-lay it on the right-half. (I'll then change with the colors and the overlaying so that someone with blue-cyan 3D glasses can view the video).

I tried to attach a single NetStream to two video objects and offset them, but that only let the stream play on one object.

Any suggestions?

答:
Since a stream is by definition a more or less continuous flow of small bits of data, rather than an object of fixed length, you can never access two different positions of a NetStream at the same time. You could try to "jump" between positions from frame to frame, producing a kind of "shutter" effect , but that would probably not perform well.

You can, however, let the video objects share the same NetConnection, and have two NetStream instances load the same movie, or you could just have your content for the left eye and right eye in two separate FLVs playing at the same time. You would have to take care of synchronization, though, and there might by slight inconsistencies.

If you are targeting Flash Player 10.1 or later, you can load both FLVs into memory as a byteArray, and then use NetStream.appendBytes to play them.  This should take care of the synching problems.


问:
Detect if the app was launched/opened from a push notification
Is it possible to know if the app was launched/opened from a push notification?

I guess the launching event can be caught here:

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    if (launchOptions != nil) {
         // Launched from push notification
         NSDictionary *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

    }
}
</code>```

However, how can I detect it was opened from a push notification when the app was in background?

答:
When app is in background as shanegao you can use

```<code>- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    if ( application.applicationState == UIApplicationStateInactive || application.applicationState == UIApplicationStateBackground  )
    {
         //opened from a push notification when the app was on background
    }
}
</code>```

But if you want to launch the application and when app is closed and you want to debug your application you can go to Edit Scheme and in left menu select Run and then in launch select Wait for executable to be launched and then you application launch when you click on push notification

Edit Scheme > Run > Wait for executable to be launched

Body:
Is it possible to know if the app was launched/opened from a push notification?

I guess the launching event can be caught here:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    if (launchOptions != nil) {
         // Launched from push notification
         NSDictionary *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

    }
}

However, how can I detect it was opened from a push notification when the app was in background?

Body:
When app is in background as shanegao you can use

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    if ( application.applicationState == UIApplicationStateInactive || application.applicationState == UIApplicationStateBackground  )
    {
         //opened from a push notification when the app was on background
    }
}

But if you want to launch the application and when app is closed and you want to debug your application you can go to Edit Scheme and in left menu select Run and then in launch select Wait for executable to be launched and then you application launch when you click on push notification

Edit Scheme > Run > Wait for executable to be launched


问:
The module has been successfully installed but then it's not found when imported? - Python
I'm trying to use the graphviz Python module and I've run into this problem:
I pip installed it in my command prompt, but it's not showing up in IPython.  I have additionally a Python 3.5 (32-bit) interpreter where it IS showing up, but I'm trying to figure out how to have it installed so it works in IPython.

I've been recommended to include the sys.path for each of the interpreters.

Anyone have any ideas as to how I'd change it?

答:
Your system python is 3.5.2
While IPython appears to be using 3.6 based on the sys.path output.

Try pip3.6 install graphviz


问:
How to upload multiple images in multipart using Alamofire?
I am stuck in uploading multiple images in multipart using Alamofire. Can any one help me?
Thanks in advance!!

For more details, I am using this code to create body part of images data:

```<code>func imageArrayToNSData(array: [UIImage],boundary:String) -> NSData {
    let body = NSMutableData()
    var i = 0;
    for image in array{
        let filename = "image\(i).jpg"
        let data = UIImageJPEGRepresentation(image,0.8);
        let mimetype = "image/jpeg"
        let key = "product_images"
        body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(filename)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("Content-Type: \(mimetype)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData(data!)
        body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        i += 1
    }

    body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    return body
}
</code>```

to upload I am using :

```<code>        Alamofire.upload(.POST, EDIT_PRODUCT_URL, headers: ["Accept": "application/json","Content-Type":"application/json"], multipartFormData: { (formData) in

        if productImages.count>0{
            let boundary = generateBoundaryString()
            let imageData = CommonClass.imageArrayToNSData(productImages,boundary: boundary)
            formData.appendBodyPart(data: imageData, name: "product_images", mimeType: "image/jpeg")
        }

        for (key, value) in params {
            if value is [String]{
                let data = CommonClass.stringArrayToNSData(value as! [String])
                formData.appendBodyPart(data:data , name: key)
            }else if value is String{
                formData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
            }else if let v = value as? Bool{
                var bValue = v
                let d = NSData(bytes: &bValue, length: sizeof(Bool))
                formData.appendBodyPart(data: d, name: key)
            }
        }

    }) { (encodingResult) in
        switch encodingResult {
        case .Success(let upload, _, _):
            KVNProgress.showProgress(CGFloat(0), status:"0% Sent")
            upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
                // This closure is NOT called on the main queue for performance
                // reasons. To update your ui, dispatch to the main queue.
                dispatch_async(dispatch_get_main_queue()) {
                    let prg = Int((CGFloat(totalBytesWritten)*100)/CGFloat(totalBytesExpectedToWrite))
                    if prg == 100{
                        KVNProgress.showSuccessWithStatus("Created")
                    }
                    KVNProgress.updateStatus("\(prg)% Sent")
                    KVNProgress.updateProgress(CGFloat(Float(prg)/100.0), animated: true)
                }
            }
            upload.responseJSON { response in
                CommonClass.hideLoader()
                switch response.result {
                case .Success:
                    if let value = response.result.value {
                        let json = JSON(value)
                        print_debug("edit Product JSON is\n\(json)");
                        completionBlock(json)
                    }else{
                        completionBlock(nil)
                    }
                case .Failure(let error):
                    print_debug(error.description)
                    showErrorWithMessage("Oops! Couldn't connect to server!")
                    completionBlock(nil)
                }
            }

        case .Failure(let encodingError):
            print(encodingError)
        }
    }
</code>```

Can any one please let me suggest the way to upload multiple files in multipart using Alamofire?

答:
In Swift 3 and above
Just append "[]" with image key identifier to treat it as array of images.

```<code>Alamofire.upload(multipartFormData: { multipartFormData in
            // import image to request
            for imageData in imagesData {
                multipartFormData.append(imageData, withName: "\(imageParamName)[]", fileName: "\(Date().timeIntervalSince1970).jpeg", mimeType: "image/jpeg")
            }
            for (key, value) in parameters {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }
        }, to: urlString,

            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in

                    }
                case .failure(let error):
                    print(error)
                }

        })
</code>```

Body:
I am stuck in uploading multiple images in multipart using Alamofire. Can any one help me?
Thanks in advance!!

For more details, I am using this code to create body part of images data:

func imageArrayToNSData(array: [UIImage],boundary:String) -> NSData {
    let body = NSMutableData()
    var i = 0;
    for image in array{
        let filename = "image\(i).jpg"
        let data = UIImageJPEGRepresentation(image,0.8);
        let mimetype = "image/jpeg"
        let key = "product_images"
        body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(filename)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("Content-Type: \(mimetype)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData(data!)
        body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        i += 1
    }

    body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    return body
}

to upload I am using :

        Alamofire.upload(.POST, EDIT_PRODUCT_URL, headers: ["Accept": "application/json","Content-Type":"application/json"], multipartFormData: { (formData) in

        if productImages.count>0{
            let boundary = generateBoundaryString()
            let imageData = CommonClass.imageArrayToNSData(productImages,boundary: boundary)
            formData.appendBodyPart(data: imageData, name: "product_images", mimeType: "image/jpeg")
        }

        for (key, value) in params {
            if value is [String]{
                let data = CommonClass.stringArrayToNSData(value as! [String])
                formData.appendBodyPart(data:data , name: key)
            }else if value is String{
                formData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
            }else if let v = value as? Bool{
                var bValue = v
                let d = NSData(bytes: &bValue, length: sizeof(Bool))
                formData.appendBodyPart(data: d, name: key)
            }
        }

    }) { (encodingResult) in
        switch encodingResult {
        case .Success(let upload, _, _):
            KVNProgress.showProgress(CGFloat(0), status:"0% Sent")
            upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
                // This closure is NOT called on the main queue for performance
                // reasons. To update your ui, dispatch to the main queue.
                dispatch_async(dispatch_get_main_queue()) {
                    let prg = Int((CGFloat(totalBytesWritten)*100)/CGFloat(totalBytesExpectedToWrite))
                    if prg == 100{
                        KVNProgress.showSuccessWithStatus("Created")
                    }
                    KVNProgress.updateStatus("\(prg)% Sent")
                    KVNProgress.updateProgress(CGFloat(Float(prg)/100.0), animated: true)
                }
            }
            upload.responseJSON { response in
                CommonClass.hideLoader()
                switch response.result {
                case .Success:
                    if let value = response.result.value {
                        let json = JSON(value)
                        print_debug("edit Product JSON is\n\(json)");
                        completionBlock(json)
                    }else{
                        completionBlock(nil)
                    }
                case .Failure(let error):
                    print_debug(error.description)
                    showErrorWithMessage("Oops! Couldn't connect to server!")
                    completionBlock(nil)
                }
            }

        case .Failure(let encodingError):
            print(encodingError)
        }
    }

Can any one please let me suggest the way to upload multiple files in multipart using Alamofire?

Body:
In Swift 3 and above
Just append "[]" with image key identifier to treat it as array of images.

Alamofire.upload(multipartFormData: { multipartFormData in
            // import image to request
            for imageData in imagesData {
                multipartFormData.append(imageData, withName: "\(imageParamName)[]", fileName: "\(Date().timeIntervalSince1970).jpeg", mimeType: "image/jpeg")
            }
            for (key, value) in parameters {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }
        }, to: urlString,

            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in

                    }
                case .failure(let error):
                    print(error)
                }

        })


问:
How to check if 2 different format date strings is a valid dates?
I need to check if 2 different format date strings is a valid dates. The formats are: YYYY-MM-DD and YYYY.MM.DD. I found just only one date string format validation, like so:

```<code>function validateDate($date)
{
    $d = DateTime::createFromFormat('Y-m-d', $date);
    return $d && $d->format('Y-m-d') == $date;
}
</code>```

function was copied from this answer or php.net

But how about two date formats validation? How to solve it? Thanks for any help

答:
Copy the original function, where you specify format as 2nd parameter, and then run function twice; as already mentioned in the comments.

```<code>function validateDate($date, $format = 'Y-m-d H:i:s')
{
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

$isValid = validDate($date, 'Y-m-d') || validDate($date, 'Y.m.d');
</code>```

function was copied from this answer or php.net

Body:
I need to check if 2 different format date strings is a valid dates. The formats are: YYYY-MM-DD and YYYY.MM.DD. I found just only one date string format validation, like so:

function validateDate($date)
{
    $d = DateTime::createFromFormat('Y-m-d', $date);
    return $d && $d->format('Y-m-d') == $date;
}

function was copied from this answer or php.net

But how about two date formats validation? How to solve it? Thanks for any help

Body:
Copy the original function, where you specify format as 2nd parameter, and then run function twice; as already mentioned in the comments.

function validateDate($date, $format = 'Y-m-d H:i:s')
{
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

$isValid = validDate($date, 'Y-m-d') || validDate($date, 'Y.m.d');

function was copied from this answer or php.net


问:
How to swap the elements in a list while keeping their index the same if you don't know the index (Python)
Say I have these two lists:

```<code>list1=["Green","2","Blue","4"]
list2=["1","Orange","3","red"]
</code>```

If I wanted to swap the '3' with 'blue' how would I do if it if I don't already know the positions of the elements in the list?

I'm using Python 2.7

Body:
Say I have these two lists:

list1=["Green","2","Blue","4"]
list2=["1","Orange","3","red"]

If I wanted to swap the '3' with 'blue' how would I do if it if I don't already know the positions of the elements in the list?

I'm using Python 2.7

Body:
list1=["Green","2","Blue","4"]
list2=["1","Orange","3","red"]

l1 = list1.index("Blue")
l2 = list2.index("3")

list1[l1], list2[l2] = list2[l2], list1[l1]


问:
Mariadb-server 10.2. fresh install in debian 8 shows error
I have followed the link for installation .

https://downloads.mariadb.org/mariadb/repositories/#mirror=23Media&distro=Debian&distro_release=jessie--jessie&version=10.2

After adding Repo.list and keys , it started installing .But ended up with the following error message

Unable to set password for the MariaDB "root" user
An error occurred while setting the password for the MariaDB administrative user. This may have happened because the account already has a password, or because of a communication problem with the MariaDB server. You should check the account's password after the package installation.

But Mariadb-10.0 , 10.1 distributions are installing properly and working fine .

答:
Try to access MariaDb in CLI without a password.

```<code>mysql -u root
</code>```

If you can do that, you can then just set a password for a user.

Body:
Try to access MariaDb in CLI without a password.

mysql -u root

If you can do that, you can then just set a password for a user.


问:
Why validation is not working?
corporate.html

```<code>          <form #f="ngForm" name="corporateProfileForm" ng-submit="corporateFrmSave(objDS, objDSCurrency)" novalidate="">
             <div class="row  form-group">
               <div class="col-md-12" >
                  <input type="text" *ngIf="formData"  [(ngModel)]="formData.Corporate_Id"  id="corpid" title="Corporate ID" tab-index="1" name="corpid" maxlength="20"  #corpid="ngModel"  required/>
                 <label for="corp"><b>Corporate ID</b></label>
                 <div *ngIf="corpid.invalid && (corpid.dirty || corpid.touched)"  class="alert alert-danger">
                  <div *ngIf="corpid.errors.required">
                       Name is required.
                   </div>
                   <div *ngIf="ncorpidame.errors.minlength">
                       Name must be at least 4 characters long.
                   </div>
                   <div *ngIf="corpid.errors.forbiddenName">
                       Name cannot be Bob.
                   </div>

                  </div>
                   </div>
                </div>
           </form>
</code>```

Iam getting error message as

ERROR TypeError: Cannot read property 'invalid' of undefined

答:
Make sure you define your variable with this structure:

TS file

```<code>export class ContactComponent implements OnInit {

  myform: any;
  corpid: FormControl;

  constructor() {

   }
  ngOnInit() {
    this.createFormControls();
    this.createForm();
  }

  createFormControls() {
    this.corpid= new FormControl('', Validators.required);
  }

  createForm() {
    this.myform = new FormGroup({
      corpid: this.corpid,
    });
  }
</code>```

HTML file

```<code><div class="md-form form-sm form-group"
     [ngClass]="{
     'invalid': corpid.invalid && (corpid.dirty || corpid.touched),
     'valid': corpid.valid && (corpid.dirty || corpid.touched)
     }">
<i class="fa fa-user prefix"></i>
<input
    type="text" id="corpid" class="form-control"
    required
    [formControlName]="'corpid'">
    <label for="corpid" class="">Your corpid</label>
</div>

<div class="form-control-feedback"
     *ngIf="corpid.errors && (corpid.dirty || corpid.touched)">
  <p *ngIf="corpid.errors.required">corpid is required</p>
</div>
</code>```

It's hard to tell because issue is not in your HTML snipped but in .ts file.
I hope my Code will be helpfull

Title: Why validation is not working?

Body:
corporate.html

          <form #f="ngForm" name="corporateProfileForm" ng-submit="corporateFrmSave(objDS, objDSCurrency)" novalidate="">

                  <input type="text" *ngIf="formData"  [(ngModel)]="formData.Corporate_Id"  id="corpid" title="Corporate ID" tab-index="1" name="corpid" maxlength="20"  #corpid="ngModel"  required/>
                 Corporate ID

                       Name is required.

                       Name must be at least 4 characters long.

                       Name cannot be Bob.

           </form>

Iam getting error message as

ERROR TypeError: Cannot read property 'invalid' of undefined

Body:
Make sure you define your variable with this structure:

TS file

export class ContactComponent implements OnInit {

  myform: any;
  corpid: FormControl;

  constructor() {

   }
  ngOnInit() {
    this.createFormControls();
    this.createForm();
  }

  createFormControls() {
    this.corpid= new FormControl('', Validators.required);
  }

  createForm() {
    this.myform = new FormGroup({
      corpid: this.corpid,
    });
  }

HTML file

<div class="md-form form-sm form-group"
     [ngClass]="{
     'invalid': corpid.invalid && (corpid.dirty || corpid.touched),
     'valid': corpid.valid && (corpid.dirty || corpid.touched)
     }">
<i class="fa fa-user prefix"></i>
<input
    type="text" id="corpid" class="form-control"
    required
    [formControlName]="'corpid'">
    <label for="corpid" class="">Your corpid</label>
</div>

<div class="form-control-feedback"
     *ngIf="corpid.errors && (corpid.dirty || corpid.touched)">
  <p *ngIf="corpid.errors.required">corpid is required</p>
</div>

It's hard to tell because issue is not in your HTML snipped but in .ts file.
I hope my Code will be helpfull


问:
Using Python and Flask
Python with Flask
This is my code:

```<code>word=input("Type Something: ")
listofwords=word.split()
wordfreq = []
for w in listofwords:
    wordfreq.append(listofwords.count(w))
    print("Word: "+str(listofwords)+ "\n")
    print("Count: "+str(wordfreq) + "\n")
</code>```

My code works fine. My only problem is that it prints it out horizontally:
Word: ['is', 'the', 'bus', 'at', 'the', 'terminal']
Count: [1, 2, 1, 1, 2, 1]

How do I have my results printout vertically like this:
Word    Count
"is"    1
"the"   2
"bus"   1
"at"    1
"the"   2
"terminal" 1

Also, which parts of my code should I put under "tr" and "td" in the table section of my html. I already have Word and Count under "th" and it works fine.

答:
In python 3.x: You must call additional the function:

```<code>print()
</code>```

For example:

```<code>for w in listofwords:
    wordfreq.append(listofwords.count(w))
    print("Word: "+str(listofwords))
    print()
    print("Count: "+str(wordfreq))
    print()
</code>```

More information you can get here.

Title: Using Python and Flask

Body:
Python with Flask
This is my code:

word=input("Type Something: ")
listofwords=word.split()
wordfreq = []
for w in listofwords:
    wordfreq.append(listofwords.count(w))
    print("Word: "+str(listofwords)+ "\n")
    print("Count: "+str(wordfreq) + "\n")

My code works fine. My only problem is that it prints it out horizontally:
Word: ['is', 'the', 'bus', 'at', 'the', 'terminal']
Count: [1, 2, 1, 1, 2, 1]

How do I have my results printout vertically like this:
Word    Count
"is"    1
"the"   2
"bus"   1
"at"    1
"the"   2
"terminal" 1

Also, which parts of my code should I put under "tr" and "td" in the table section of my html. I already have Word and Count under "th" and it works fine.

Body:
In python 3.x: You must call additional the function:

print()

For example:

for w in listofwords:
    wordfreq.append(listofwords.count(w))
    print("Word: "+str(listofwords))
    print()
    print("Count: "+str(wordfreq))
    print()

More information you can get here.


问:
How to read xml code from svg extension svg
So i'm having problems reading some xml.
I need to read the <path> attributes.

The SVG looks like this:

```<code><?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="700pt" height="820pt" viewBox="60 25 500 600"
  version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" >
  <g id="id1">
    <g id="id3">
      <g id="id3">

 <path clip-path="url(#SVG_CP_1)" fill="#000000" city="Amsterdam" />

</g>
</g>
</g>
</svg>
</code>```

my code:

```<code>XDocument xdoc = XDocument.Load("D:/Users/me/Desktop/Website/files/test.svg");
            xdoc.Descendants("path").Select(p => new
            {
                city= p.Attribute("city").Value,

            }).ToList().ForEach(p =>
            {
                html.Append("City:  " + p.city+ "<br>");

            });
</code>```

Now this code works perfectly when I exclude <svg width='700pt' etc... > from the svg file . But I need it in my file.

答:
The root element svg contains default namespace declaration which URI is http://www.w3.org/2000/svg. Notice that all descendant elements without prefix implicitly inherit ancestor's default namespace.

Now to reference element in namespace, you can use combination of XNamespace and the target element's local name :

```<code>XDocument xdoc = ...;
XNamespace ns = "http://www.w3.org/2000/svg";
xdoc.Descendants(ns+"path").Select(p => new
{
    ....
})
....
</code>```

Body:
So i'm having problems reading some xml.
I need to read the <path> attributes.

The SVG looks like this:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="700pt" height="820pt" viewBox="60 25 500 600"
  version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" >
  <g id="id1">
    <g id="id3">
      <g id="id3">

 <path clip-path="url(#SVG_CP_1)" fill="#000000" city="Amsterdam" />

</g>
</g>
</g>
</svg>

my code:

XDocument xdoc = XDocument.Load("D:/Users/me/Desktop/Website/files/test.svg");
            xdoc.Descendants("path").Select(p => new
            {
                city= p.Attribute("city").Value,

            }).ToList().ForEach(p =>
            {
                html.Append("City:  " + p.city+ "
");

            });

Now this code works perfectly when I exclude <svg width='700pt' etc... > from the svg file . But I need it in my file.

Body:
The root element svg contains default namespace declaration which URI is http://www.w3.org/2000/svg. Notice that all descendant elements without prefix implicitly inherit ancestor's default namespace.

Now to reference element in namespace, you can use combination of XNamespace and the target element's local name :

XDocument xdoc = ...;
XNamespace ns = "http://www.w3.org/2000/svg";
xdoc.Descendants(ns+"path").Select(p => new
{
    ....
})
....